I'm attempting to read from an already created file that is 5 x 5 into a 2D array. In my program I've tried both an eof() method and a boolean way to determine the end of the file. The boolean way did actually reading something into the array, but the numbers are totally incorrect from what's in the file. The eof() method doesn't even seem to read anything in.
If you look at line 11, your const indicates you're reading in five rows. What you've copied from your file, however, only has four row, so on the last iteration of your loop on line 30, you're reading in garbage.
Edit: I'd also recommend that if you're going to pass both rows and columns as parameters as you do in your readSquare function, that you still use nested for loops to read in your file. instead of using magic numbers like you do on line 32.
@Keene, You're right I was missing a line in the input file. However, I added that and what my program is reading in is still garbled. I also updated the for loop from line 32? Further suggestions...
My only other suggestion would be that the file path you're providing is incorrect. It's typically good practice to check to see if the file opened successfully. If it is indeed because the file didn't open successfully, you're running into a unique problem in that you're not using .eof(). If you were, you'd just get an infinite loop and no output. I'd suggest putting the file in the same directory as your .cpp file, and referring to it simply as fileInput.open("file.txt");
if ( !fileInput.is_open() ) return; //if the file didn't open correctly, quit the function
while ( !fileInput.eof() ) //this is a viable option now
{
for (int i = 0 ; i < ROW1; i++)
{
for (int j = 0 ; j < COL1; j++) //you had the incorrect const here originally.
{
fileInput >> magicArray1[i][j];
}
}
}
fileInput.close();
for (int i = 0; i < ROW1; i++)
{
for (int j = 0; j < COL1; j++)
{
cout << magicArray1[i][j] << " "; //space between columns
}
cout << endl; //newlines for rows
}
You don't need to pass your constants into the function if you just declare them outside of main, they then become global to your program and don't need to be passed.