Reputation: 1
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();
}
Upvotes: 0
Views: 123
Reputation: 361732
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. 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
Upvotes: 3
Reputation: 22690
You can read from fstream to int using operator>>
:
int n;
infile >> n;
Upvotes: 0