c++ - 无法从包含 2 列的 txt 文件中读取整数 (C++)

标签 c++ text-files

我必须编写一段代码,提示用户输入文件名(包含 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/

相关文章:

c++ - pthread_join() 在 C++ 中使用 pthreads 的逻辑错误

php - php 中的 a+(读取/追加)与 a(追加)有何不同

c++ - 为什么我不能将 [](auto&&...){} 转换为 std::function<void()>?

c++ - 区分两个值相等、名称不同的枚举值

c - c - 如何在c中比fprintf更快地写入文本文件?

swift - Xcode 7.1 测试版 : Content Of File Error

text-files - 如何在Windows上读取大文本文件?

c++ - 如何从文本文件中填充指针数组?

c++ - 是否有一种有效的标准算法来栅格包括其内部区域的多边形

c++ - 多文件访问单例类