I was writing some code that needs to take values one by one and store them into a 2D int array, and was having differences when taking values from file and manually inputting them. It looks like this :
int ar[9][9];
while(!cin.eof()){
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
{
cin.get(temp);
ar[i][j] = temp -48;
}
}
I would pass in input from the terminal running it like
./prog.out < inp.txt
and get the value of -38 for a random value like ar[0][1], but i would get the correct value when I type
./prog.out
12345678 ^d
getting 2 when printing ar[0][1], which is correct. Why should this code be acting differently? Is it because the file is the full 81 characters followed by \n and eof, compared to just a couple values followed by ^d?
Thanks.
You’re not checking
eofat the right time – it’s set when an attempt to read a value hit eof, not beforehand – so the behaviour’s a bit random. And, you’re assuming that not being at eof means you can read 81 values… how do you know you weren’t one newline away fromeof? And you’re not checking the success ofcin.get()….I recommend simply