2017-07-17 75 views
-3

当我将信息转换为整数并打印出数组时,输出仅为0。 info中的每个元素都是从文本文件中获取的字符串形式输入的数字。例如:513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79.我使用strtok删除行中的空格,并将数字输入到信息中。当我打印出所有的数字都在那里。我如何让这些转换正确?当将字符串数组转换为整数数组时,元素变为0

string info[1000] 
int student[18]; 
for (int i=1; i<18; i++){ 
    //cout << info[i] << endl; 
    stringstream convert(info[i]); 
    convert << student[n]; 
    cout << student[n] << endl; 
    n++; 
} 
+1

是什么类型'str'?什么是'n'(以及与'i'相关的情况如何)? – user0042

+0

此代码不能编译 – dlatikay

+2

请注意“<<" and">>”之间的区别。 (如果你没有编写不必要的通用代码,编译器会帮助你。) – molbdnilo

回答

0

字符串流是我最喜欢的工具。它们会自动转换数据类型(大部分时间),就像cin和cout一样。这是一个字符串流的例子。这些都包括在库

string info = "513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79"; 
int student[18]; 

stringstream ss(info); 

for (int i=0; i< 18; i++){ 
    ss >> student[i]; 
    cout << student[i] << endl;; 
} 

这里是一个REPL https://repl.it/J5nQ

相关问题