【问题标题】:c++ reading comma separated with unwanted resultc ++读取逗号与不需要的结果分隔
【发布时间】: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++;
}

【问题讨论】:

  • 经典菜鸟错误:eof() or good() in loop condition.
  • getline() 仅适用于字符串,不适用于整数。要获取 int,您需要先将其作为字符串读取,然后使用 std::stoi 之类的内容进行解析。
  • @FeiXiang,感谢您的回复。我按照您的建议将 good() 替换为 eof() ,还使用 ​​stoi() 将字符串/字符数转换为整数。它仍然没有正确输出。
  • 你能发布新代码吗?
  • @FeiXiang,刚刚更新了。

标签: c++ file ifstream getline


【解决方案1】:

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

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

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

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

【讨论】:

  • 我还是没弄好。对不起,我累了。
猜你喜欢
  • 2013-10-16
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
相关资源
最近更新 更多