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. 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>>
:
int n;
infile >> n;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.