逐个整数文件读取

integer by integer file reading

本文关键字:读取 文件 整数      更新时间:2023-10-16

我想读取文件,以便它应该逐个整数地读取。我已经一行一行地阅读了它,但我想逐个整数地阅读它。

这是我的代码:

void input_class::read_array()
{    
        infile.open ("time.txt");
        while(!infile.eof()) // To get you all the lines.
        {
            string lineString;
            getline(infile,lineString); // Saves the line in STRING
            inputFile+=lineString;
        }
        cout<<inputFile<<endl<<endl<<endl;
        cout<<inputFile[5];
        infile.close();
}

你应该这样做:

#include <vector>
std::vector<int> ints;
int num;
infile.open ("time.txt");
while( infile >> num)
{
    ints.push_back(num);
}

循环将在到达 EOF 时退出,或者尝试读取非整数。要详细了解循环的工作原理,请阅读我的答案 这里, 这里 和 这里.

另一种方法是:

#include <vector>
#include <iterator>
infile.open ("time.txt");
std::istream_iterator<int> begin(infile), end;
std::vector<int> ints(begin, end); //populate the vector with the input ints
您可以使用

operator>>从 fstream 读取到 int

int n;
infile >> n;