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
to
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: