gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:44:20 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于c++ - 尝试从文件读取输入后代码无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com