0

Lets say I have a txt file list.txt

The txt file has list of integers ,

88
894
79
35

Now I am able to open the file and display the contents in it but not able to store it in an integer array.

int main()
{
     ifstream fin;
     fin.open("list.txt");
     char ch;
     int a[4],i=0;
     while((!fin.eof())&&(i<4))
     {
          fin.get(ch);
          a[i]=(int)ch;
          cout<<a[i]<<"\n";
          i++;
     }
     fin.close();
     return 0;
}

Please help!!

akash
  • 22,664
  • 11
  • 59
  • 87
livzz
  • 73
  • 1
  • 7
  • 2
    [Why looping on eof() is bad](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Galik Oct 25 '14 at 12:15
  • possible duplicate of [Convert char to int in C and C++](http://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) – Philipp Meissner Oct 25 '14 at 12:22

2 Answers2

3

You can use >> to read text-formatted values:

fin >> a[i]

You should check for the end of the file after trying to read, since that flag isn't set until a read fails. For example:

while (i < 4 && fin >> a[i]) {
    ++i;
}

Note that the bound needs to be the size of the array; yours is one larger, so you might overrun the array if there are too many values in the file.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Try the following

#include <iostream>
#include <fstream>

int main()
{
     const size_t N = 4;
     int a[N];

     std::ifstream fin( "list.txt" );

     size_t i = 0;

     while ( i < N && fin >> a[i] ) i++;

     while ( i != 0 ) std::cout << a[--i] << std::endl;

     return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335