c ++用不需要的结果分隔逗号

时间:2018-04-13 02:47:38

标签: c++ file ifstream getline

首先,请理解我正在学习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++;
}

1 个答案:

答案 0 :(得分:2)

不确定到底发生了什么,因为它甚至不应该编译。您使用std::atof(接受char*)而不是std::stof(接受std::string)。

此外,飞翔的链接表明在这种情况下你根本不应该使用eof();你应该使用:

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

在修复之后,似乎工作正常:ideone example using cin