整数文件读取整数

时间:2012-04-26 14:25:45

标签: c++

我想读取文件,以便它应该按整数读取整数。我已经逐行读了它,但我想用整数读它。

这是我的代码:

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();
}

2 个答案:

答案 0 :(得分:3)

你应该这样做:

#include <vector>

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

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

另一种方法是:

#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

答案 1 :(得分:0)

您可以使用operator>>

从fstream读取到int
int n;
infile >> n;
相关问题