尝试从文件读取输入后,代码无法正常运行

时间:2013-12-04 03:01:53

标签: c++

我的输入文件设置如下:

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

但阅读似乎失败了。谁能在这帮助我?

2 个答案:

答案 0 :(得分:2)

问题1:getline>>。这篇文章的解决方案: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;
  }
}

答案 1 :(得分:0)

这会有效..

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

希望这有帮助。