【问题标题】:Code is failing to run properly after trying to read input from file尝试从文件读取输入后代码无法正常运行
【发布时间】:2013-12-20 09:16:12
【问题描述】:

我有一个这样设置的输入文件:

Hello there
1 4
Goodbye now
4.9 3

我尝试这样读取数据:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
    ifstream input("file.txt");
    string name;
    double num1, num2;

    while(!input.eof()){
        getline(input, name);
        input >> num1;
        input >> num2;

        cout << name << endl;
        cout << num1 << " " << num2 << endl;
    }
}

但读取似乎失败了。有人可以帮我吗?

【问题讨论】:

  • getline 没有从流中删除 \n
  • 首选"\n"而不是std::endl,除非你有理由刷新。

标签: c++


【解决方案1】:

问题 1:getline&gt;&gt;。这篇文章的解决方案:C++ iostream: Using cin >> var and getline(cin, var) input errors

问题 2:inupt.eof() 测试循环结束,本帖:Why is iostream::eof inside a loop condition considered wrong?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
  ifstream input("dat.txt");
  string name;
  double num1, num2;

  while (getline(input, name)) {  // getline fails at the end of file
    input >> num1 >> num2;
    input.ignore();
    cout << name << endl;
    cout << num1 << " " << num2 << endl;
  }
}

【讨论】:

  • 问题中提到的文件内容的代码我得到的输出是 Hello there \n 1 4 \n 0 4
  • @AbhishekBagchi 有趣的是,我在Ubuntu 13.10 上使用gcc 4.8 得到了正确的输出。
【解决方案2】:

这会起作用..

ifstream input("command2");
string name;
double num1, num2;

int x;

while(getline(input, name)){
    input >> num1;
    input >> num2;
    input.clear();
    cout << name << endl;
    cout << num1 << " " << num2 << endl;
    string dummy;
    getline(input,dummy);
}

我编写第二个 getline() 以确保读取 1 4 行的 \n。

没有它,我得到的是

Hello there
1 4

0 4
Goodbye now
4.9 3

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2019-01-08
    • 1970-01-01
    • 2023-02-22
    • 2016-05-31
    • 1970-01-01
    • 2011-12-16
    相关资源
    最近更新 更多