I have a problem with filling a fixed size 2D array with the fgetc()
function.
My program should read only '-'
, '+'
or '!'
and the chars entered on one line must be equal to size of the columns.
Here is the problematic part of my code:
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
c = fgetc( stdin );
if( (c != '-') && (c != '+') && (c != '!') ) {
printf( "Incorrect value.\n" );
return 1;
}
array[i][j] = c;
}
if(array[i+1][0] != '\n') {
printf( "Incorrect value (size does not equal to columns).\n" );
return 1;
}
}/*---end of for---*/
Here is how I understand it:
fgetc()
scans newline char ('\n') as well and puts it in the following row - which means that array[1][0]
should be '\n'
. If the user enter more chars than cols are set to, it will be other character than newline and program will end with an error. However this does not work.
Is there a better way to ignore newline from a stdin and check if the user did not enter more chars than specified earlier?
Test the value against '\n'
and use int
.
Do not save the return value from fgetc()
into the char
array and later test. This loses the ability to distinguish EOF
from other char
.
When an '\n'
is expected (or EOF), that is good.
Recommend using positive logic tests as it is easier to understand
for (i = 0; i < rows; i++) {
int c;
for (j = 0; j < cols; j++) {
c = fgetc( stdin );
if (c == '-' || c == '+' || c == '!') {
array[i][j] = c;
} else {
puts("Incorrect value.");
return 1;
}
}
c = fgetc( stdin ); // Read and consume the end-of-line
if (!(c == '\n' || c == EOF)) {
printf( "Incorrect value (size does not equal to columns).\n" );
return 1;
}
}