[英]integer by integer file reading
I want to read file so that it should read integer by integer. 我想读取文件,以便它应按整数读取整数。 I have read it line by line but i want to read it integer by integer.
我已经逐行读取了它,但是我想逐个整数读取它。
This is my code: 这是我的代码:
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();
}
You should do this: 你应该做这个:
#include <vector>
std::vector<int> ints;
int num;
infile.open ("time.txt");
while( infile >> num)
{
ints.push_back(num);
}
The loop will exit when it reaches EOF, or it attempts to read a non-integer. 当循环到达EOF或尝试读取非整数时,该循环将退出。 To know in details as to how the loop works, read my answer here , here and here .
要详细了解循环的工作原理,请在此处 , 此处和此处阅读我的答案。
Another way to do that is this: 另一种方法是:
#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
You can read from fstream to int using operator>>
: 您可以使用
operator>>
从fstream读取到int:
int n;
infile >> n;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.