livzz
livzz

Reputation: 83

How cast char to int in C++? (File Handling)

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!!

Upvotes: 0

Views: 100

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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;
}

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254431

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.

Upvotes: 3

Related Questions