我在使用 fgetc()
函数填充固定大小的二维数组时遇到问题。
我的程序应该只读取 '-'
、'+'
或 '!'
并且在一行中输入的字符必须相等列的大小。
这是我的代码中有问题的部分:
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---*/
我是这样理解的:
fgetc()
也扫描换行符 ('\n') 并将其放入下一行 - 这意味着 array[1][0]
应该为 '\n'
。如果用户输入的字符多于 cols 设置的字符数,它将是除换行符之外的其他字符,程序将以错误结束。但是,这不起作用。
有没有更好的方法来忽略来自标准输入的换行符并检查用户是否输入了比之前指定的更多的字符?
最佳答案
根据 '\n'
测试值并使用 int
。
不要将fgetc()
的返回值保存到char
数组中,稍后再进行测试。这失去了区分 EOF
和其他 char
的能力。
当需要 '\n'
(或 EOF)时,这很好。
推荐使用正逻辑测试,更容易理解
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;
}
}
关于c - 我应该如何使用 fgetc 忽略来自 stdin 的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020705/