0

In my program, the name of the file with the values (at most 2-digit numbers) to be read is given in the terminal and my main() is as below:

int main ( int argc, char *argv[] )
{
   //assume argv[1] is a filename to open
   ifstream the_file ( argv[1] )
   if ( !the_file.is_open() ){
      cout<<"Could not open file" << endl;
      return 0;
   }

   char x;
   int array[10];
   int x_int;
   while ( the_file.get ( x ) ){
        for (int i=0; i<10;i++){
             array[i] = (int)x;
        }
   }
      
}

However, I am getting some odd number.

My mistake is definitely at array[i] = (int)x; line, but

how can I convert read char value to int? Or is there any other method to read them as int type?

I want to have the values taken from input file work as integers, not as a single digit

My actual input file (.txt) is:

75
95
1
2
45
65
98
6
7
9
cigien
  • 57,834
  • 11
  • 73
  • 112
  • What does your file contain? A sequence of digits ('0'-'9'), A sequence of numbers (possibly multi-digit), or binary data? Give an example. – interjay Nov 24 '15 at 18:15
  • @interjay, it has at most 2-digit numbers like 55, 78, 2, 4. etc. – Despicable me Nov 24 '15 at 18:20
  • 1
    So reading it one char at a time as you do in the question won't help you, and neither will converting a char to an int. Please edit the question to describe the file format and the output you want. – interjay Nov 24 '15 at 18:21

2 Answers2

4

how can I convert read char value to int?

You can fix this by just writing

array[i] = x - '0';

ASCII characters like '1' or '5' cannot be directly casted to get their numeric equivalents. Make sure you've been reading a digit character when doing so, e.g. using the std::isdigit() function.


As for your primary concern after the question edit:

Or is there any other method to read them as int type?

The usual method to read in int types is just apply the std::istream& operator>>(std::istream&, int&) like so

int array[10];
int i = 0;
int x_int;
while ( the_file >> x_int && i < 10) {
    array[i] = x_int;
    ++i;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

An easy way to solve your problem is to use getline() and read it into a char buf[MAX_LINE_LEN] where MAX_LINE_LEN is the maximum size of the input line. Instead of (int)x use atoi(buf). You will need to include stdlib.h.

You also could just use >> operator to read into array[i] directly. If you have to read one character at a time, you can use num = num * 10 + (x - '0') computation in a loop breaking on delimiters (non-digits), but this is a more complicated solution.

Sasha Pachev
  • 5,162
  • 3
  • 20
  • 20