简体   繁体   中英

Reading a file one int at a time in C++

I am working on a program that requires reading in integers from a file into a 2D array. The concept is easy and I'm generally ok with file I/O. My problem is that the file contains 20 rows of 18 numbers. The numbers are not seperated by white space. An example is:

123456789987654321
192837465564738291

I have to read each individual number into the 2D array. I have created a for loop but I'm not getting the required output from the file I/O part of the loop. Is there a way to do this or do I need to use a work around such as reading the line into a string/array and dividing it? It's driving me mad. In the code, infile has been opened and tested. GRIDSIZE has a size of 9 and grid is the 2D array

int n;

for(int i=0; i<GRIDSIZE; i++)
      {   
    for(int j=0; j<GRIDSIZE; j++)
      {
        infile.get()>>grid[i][j];//This is causing the problem
         // infile >> n //Also tried this, not working
         // grid[i][j] = n;
        cout<<grid[i][j]<<endl;
      }
      }

Calling get() on an ifstream returns a single character, casted to an int. So try changing

infile.get()>>grid[i][j];

to

grid[i][j] = infile.get();

That will give you the ASCII value of the digit. You can then use isdigit() (as noted by stefaanv) to make sure you actually have a digit, and then just subtract 0x30 (= 48 or '0') from them to get the integer values (as evident from an ASCII chart , the digits go from 0x30 to 0x39). So for instance:

int n = infile.get();
if(isdigit(n)) {
  grid[i][j] = n - '0';
}

You can use infile.get() to get a character (as in sonicwave's answer) and check with isdigit() whether you actually have an integer digit.

EDIT (after comment from adohertyd):
If the ASCII character is a digit, you can subtract ASCII character '0' from it to get the actual number.

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