【发布时间】:2018-04-13 02:47:37
【问题描述】:
首先,请理解我正在学习c++,我是一个新的蜜蜂。我试图从文件中读取逗号分隔的行。大多数情况下看起来不错,但我意识到数字是混淆的。
如您所见,输出第 4、6、7 和 9 行的前两个数字(1 和 0)弄乱了/放错了位置。非常感谢!
people.txt
0,0,Person,One,16.1
1,1,Person,Two,5
1,1,Person,Three,12
0,1,Person,Four,.2
0,0,Person,Five,10.2
0,1,Person,Six,.3
1,0,Person,Seven,12.3
1,1,Person,Eight,4.2
1,0,Person,Nine,16.4
1,1,Person,Ten,1.4
c++ 输出:
1
0,0,Person,One,16.1
0,0,Person,One,16.1
2
1,1,Person,Two,5
1,1,Person,Two,5
3
1,1,Person,Three,12
1,1,Person,Three,12
4
1,0,Person,Four,.2
0,1,Person,Four,.2
5
0,0,Person,Five,10.2
0,0,Person,Five,10.2
6
1,0,Person,Six,.3
0,1,Person,Six,.3
7
0,1,Person,Seven,12.3
1,0,Person,Seven,12.3
8
1,1,Person,Eight,4.2
1,1,Person,Eight,4.2
9
0,1,Person,Nine,16.4
1,0,Person,Nine,16.4
10
1,1,Person,Ten,1.4
1,1,Person,Ten,1.4
我的阅读代码是:
ifstream ifs;
string filename = "people.txt";
ifs.open(filename.c_str());
int lineCount = 1;
while(!ifs.eof()){
int num1, num2;
string num1Str, num2Str, num3Str, first, last, line;
float num3;
getline(ifs, line);
stringstream ss(line);
getline(ss, num1Str, ',');
getline(ss, num2Str, ',');
getline(ss, first, ',');
getline(ss, last, ',');
getline(ss, num3Str);
num1 = stoi(num1Str);
num2 = stoi(num2Str);
num3 = atof(num3Str);
cout <<lineCount<<endl<< num1 << "," << num2 << ","
<< first << "," << last <<"," << num3
<< "\n\t" << line << endl << endl;
lineCount++;
}
【问题讨论】:
-
getline()仅适用于字符串,不适用于整数。要获取 int,您需要先将其作为字符串读取,然后使用std::stoi之类的内容进行解析。 -
@FeiXiang,感谢您的回复。我按照您的建议将 good() 替换为 eof() ,还使用 stoi() 将字符串/字符数转换为整数。它仍然没有正确输出。
-
你能发布新代码吗?
-
@FeiXiang,刚刚更新了。