0

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();
}
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
Mudasir Rao
  • 1
  • 1
  • 1
  • What is the format of the file? Is it binary? If not, what are the delimiters between the integer values? – Chad Apr 26 '12 at 14:28

2 Answers2

3

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
Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

You can read from fstream to int using operator>>:

int n;
infile >> n;
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79