I am working on a program that reads a series of ints from a text file into a 2D array.
The file contains 40 lines of 81 numbers that have no spaces between them.
The problem is that when I cout the array after the loop has finished, it is outputting 2 random numbers in array[0][0] and array[0][1] before the expected output. I think it has to do with the newline/carriage return characters. The first iteration of the loop runs perfectly. Here is the code:
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array[9][9];
//Open file:
fstream ifile;
ifile.open("numbers.txt", ios::in);
if (ifile.fail())
{
cout << "Could not open numbers.txt" << endl;
return -1;
}
while (!ifile.eof())
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
int n = ifile.get();
if(isdigit(n))
{
array[i][j] = n - '0';
}
cout<<"array ["<<i<<"]["<<j<<"] is "<<array[i][j]<<endl;
}
} cout<<"This is a test"<<endl;
}
return 0;
}
The random numbers appear because you increment
jregardless of whether you write togrid[i][j].Try replacing your inner loop with: