我有一个输入文件,试图从文件中获取一些数据并显示在输出中。
文件中的数据为:
SS
0
NN
1
XX
10
YY
20
和我的代码:
ifstream inFile;
inFile.open("input.txt");
string s1, s3;
int n2, n4;
while ( inFile ) {
getline(inFile, s1);
cout << "1: " << s1 << endl;
inFile >> n2;
cout << "2: " << n2 << endl;
inFile.ignore(1000, '\n');
getline(inFile, s3);
cout << "3: " << s3 << endl;
inFile >> n4;
cout << "4: " << n4 << endl;
inFile.ignore(1000,'\n');
cout << endl;
}
检查输出时!输出是:
1: SS
2: 0
3: NN
4: 1
1:
2: 0
3: NN
4: 1
我认为我的问题应该是因为inFile.ignore()
。
你能为我解释发生了什么吗?
答案 0 :(得分:1)
while ( inFile ) { getline(inFile, s1); cout << "1: " << s1 << endl; inFile >> n2; cout << "2: " << n2 << endl;
提取失败时,您正在处理垃圾。
#include <cstdlib>
#include <string>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream inFile{ "input.txt" };
if (!inFile.is_open())
return EXIT_FAILURE;
std::string s1, s3;
int n2, n4;
while (inFile >> s1 >> n2 >> s3 >> n4)
std::cout << "1: " << s1 << "\n2: " << n2 << "\n3: " << s3 << "\n4: " << n4 << "\n\n";
}
1: SS
2: 0
3: NN
4: 1
1: XX
2: 10
3: YY
4: 20
如果字符串确实包含空格,并且两个数据集用空行分隔:
#include <limits>
// ...
while (std::getline(inFile, s1) && (inFile >> n2) &&
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n') &&
std::getline(inFile, s3) && (inFile >> n4))
{
std::cout << "1: " << s1 << "\n2: " << n2 << "\n3: " << s3 << "\n4: " << n4 << "\n\n";
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}