我必须编写一段代码,提示用户输入文件名(包含 2 列整数)。然后程序读取该文件,打印出数字集。
我的 txt 文件看起来像这样(数字用空格分隔):
2 3
5 6
7 8
8 9
5 7
我以为这很容易,但现在我卡住了。当我运行程序时,出现了这一行
“文件中没有编号。”
我将数字设置为“int”,为什么编译器不能读取数字?但是当我将类型更改为“字符串”时,数字确实出现了 O_O ,因为我稍后还需要计算这些数字的平均值,所以我不能使用字符串。
这是我的代码,感谢您的帮助TT___TT
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream in_file;
string filename;
int number;
int number1;
cout << "In order to process, please enter the file name: ";
cin >> filename;
in_file.open(filename.c_str());
if (!in_file.is_open())
{
cout << "Cannot open file" << endl;
}
else
{
in_file >> number;
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
}
system("pause");
return 0;
}
最佳答案
你的逻辑错误:
in_file >> number; // Assigns 2 from first line to number
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1) // Assigns 3 to number from first line
// and assigns 5 to number1 from second line
{
cout << number << " " << number1;
}
你只需要使用:
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
如果你必须打印“There're no number in the file.”在输出中,您可以使用:
bool gotSomeNumbers = false;
while (in_file >> number >> number1)
{
cout << number << " " << number1;
gotSomeNumbers = true;
}
if (!gotSomeNumbers)
{
cout << "There're no number in the file." << endl;
}
关于c++ - 无法从包含 2 列的 txt 文件中读取整数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35326838/