从文件中读取整数数据

Read integer data from a file

我刚刚开始使用 C++ 并正在处理代码问题,所以如果有人这样做,他们会认出这个问题,因为它是列表中的第一个问题。我需要打开一个包含 3 列 space 分隔整数值的文件。这是我的,在 fizbuz.txt 下。我需要从文件中获取整数值并将它们存储起来以供以后在程序的其他地方使用。

1 2 10
3 5 15
4 5 20
2 8 12
2 4 10
3 6 18
2 3 11
8 9 10
2 5 8
4 9 25

现在我可以很好地打开文件,并且我已经使用 getline() 使用下面的代码很好地读取文件。但是,我不希望它们是字符串格式,我希望它们是整数。所以我环顾四周,每个人基本上都说相同的符号(文件>>int1>>int2 ...)。我已经按照我在几个示例中看到的方式编写了一些代码,但它的行为根本不像他们告诉我的那样。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string filename = "fizbuz.txt";
    string line;
    int d1,d2,len;
    int i =0;
    int res1[10], res2[10], length[10];
    ifstream read (filename.c_str());
    if (read.is_open())
    {
        // while(read>>d1>>d2>>len);
        // {
        //     res1[i] = d1;
        //     res2[i] = d2;
        //     length[i] = len;
        //     i++;
        // }
        while (!read.eof())
        {
            read>>d1>>d2>>len;
            res1[i] = d1;
            res2[i] = d2;
            length[i] = len;
        }
        read.close();
    }
    else
    {
        cout << "unable to open file\n";
    }
    for (int j = 0; j < 10;j++)
    {
        cout<< res1[j] << " " << res2[j] << " " << length[j] << '\n';
    }

}

两个while循环在底部的输出函数中执行相同的操作。 fizbuz.txt 的最后一行将返回到 res1、res2 和 length 的第一个元素,所有 3 个的其余元素都是伪随机值,大概来自之前使用该内存块的任何程序。下面的 ex 输出

4 9 25
32767 32531 32767
-1407116911 4195256 -1405052128
32531 0 32531
0 0 1
0 1 0
-1405052128 807 -1404914400
32531 1 32531
-1405054976 1 -1404915256
32531 0 32531

试试这个

        while (!read.eof())
        {
            read>>d1>>d2>>len;
            res1[i] = d1;
            res2[i] = d2;
            length[i] = len;
            i++;
        }

除了您需要删除 while 行中的 ; 之外,第一个版本应该可以使用。

while (read >> d1 >> d2 >> len);
                               ^