简体   繁体   中英

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

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM