[英]C++ - Cin.ignore and get data from other File
I have an input file and trying to get some data from my file and show in the output.我有一个输入文件并试图从我的文件中获取一些数据并显示在输出中。
The data in the file is:文件中的数据是:
SS
0
NN
1
XX
10
YY
20
and my code:和我的代码:
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;
}
when checking the output!检查输出时! the output is :输出是:
1: SS
2: 0
3: NN
4: 1
1:
2: 0
3: NN
4: 1
I'm thinking my problem should be because of inFile.ignore()
.我想我的问题应该是因为inFile.ignore()
。
Could you explain for me what is going on?你能帮我解释一下这是怎么回事吗?
while ( inFile ) { getline(inFile, s1); cout << "1: " << s1 << endl; inFile >> n2; cout << "2: " << n2 << endl;
You are processing garbage when extraction fails.当提取失败时,您正在处理垃圾。
#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
If the strings could really contain whitespace and two datasets are seperated by an empty line:如果字符串确实可以包含空格并且两个数据集由空行分隔:
#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');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.