简体   繁体   English

C ++读取逗号分隔,并显示不想要的结果

[英]c++ reading comma separated with unwanted result

First of all, please understand that I'm learning c++ and I am a new bee. 首先,请理解我正在学习c ++,并且我是一只新蜜蜂。 I tried to read the comma separated lines from a file. 我试图从文件中读取逗号分隔的行。 Mostly it looks okay, but I realized that numbers were mixed up. 大多数情况下看起来还可以,但是我意识到数字是混杂的。

As you can see, output line 4, 6, 7, and 9 have their first two numbers (1 and 0) messed up/ misplaced. 如您所见,输出行4、6、7和9的前两个数字(1和0)被弄乱/放错了位置。 Much appreciated! 非常感激!

people.txt 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++ output: 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

My code to read them is: 我阅读它们的代码是:

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++;
}

Not sure exactly what was going on because it shouldn't even compile. 不知道到底发生了什么,因为它甚至不应该编译。 You are using std::atof (takes in a char* ) instead of std::stof (takes in a std::string ). 您使用的是std::atof (使用char* )而不是std::stof (使用std::string )。

Also, the link from Fei Xiang indicates you shouldn't use eof() at all in this situation; 另外, eof()的链接表明您在这种情况下根本不应该使用eof() you should use: 您应该使用:

while (std::getline(ifs, line)) {
  // use line
}

After those fixes, it seems to work fine: ideone example using cin 经过这些修复后,它似乎可以正常工作: 使用cin ideone示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM