Computer Science Canada Reading from file |
Author: | cscscs [ Tue Mar 15, 2011 6:05 pm ] |
Post subject: | Reading from file |
Hi, I would like to read in from a file that looks like something like this: OHOHOHOH HOHOOHOH HOOHHOHO OHOHOHHO ... but I would like to read it in a way where it reads every character individually and at the end of the line, it it continues on the next line. . I know the input will be 8x8. Then I want to basically put this in a 2d array but for every O we have a 1 and for every H we have a 0 field is the name of my array, i and j are rows and columns. My attempt is this: for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { int n = getchar(); if (n == 'O') { g->field[i][j] = 1; } else { g->field[i][j] = 0; } } } return g; |
Author: | DemonWasp [ Tue Mar 15, 2011 6:50 pm ] |
Post subject: | RE:Reading from file |
Don't forget to consume newline characters at the end of each line. Depending on your operating system, that may be a (char)10, (char)13, or both: (short)0x0A0D . |
Author: | OneOffDriveByPoster [ Wed Mar 16, 2011 9:32 am ] |
Post subject: | Re: RE:Reading from file |
DemonWasp @ Tue Mar 15, 2011 6:50 pm wrote: Don't forget to consume newline characters at the end of each line. Depending on your operating system, that may be a (char)10, (char)13, or both: (short)0x0A0D . Despite the evils of scanf in production code, you are better off using scanf with " %c" here. Note the space before the %. |
Author: | DtY [ Wed Mar 16, 2011 10:09 am ] |
Post subject: | Re: RE:Reading from file |
DemonWasp @ Tue Mar 15, 2011 6:50 pm wrote: Don't forget to consume newline characters at the end of each line. Depending on your operating system, that may be a (char)10, (char)13, or both: (short)0x0A0D . Doesn't the C standard say that these must always appear as \n? |
Author: | DemonWasp [ Wed Mar 16, 2011 11:32 am ] |
Post subject: | RE:Reading from file |
DtY: That depends on how you open the stream, which the OP didn't list. If you open the stream for "read", then they will appear as '\n' characters. If you open for "binary read", they will appear as whatever they are in the file. I believe (though I can't be sure) that streams like standard-input will read it as '\n'. |