我是 C 编程语言的新手,我很困惑如何使用 scanf() 作为 while 循环中的条件来捕获 scanf() 错误。
代码类似于:
while (scanf("%d", &number == 1) && other_condition)
{
...
}
如何判断何时未输入整数,以便打印出相关的错误消息?
最佳答案
听起来您正在尝试确定 scanf()
是否失败而不是其他条件。许多 C 开发人员处理此问题的方法是将结果存储在变量中。值得庆幸的是,由于赋值的计算结果是一个值,因此我们实际上可以将其作为循环的一部分来执行。
int scanf_result;
/* ... */
// We do the assignment inline...
// | then test the result
// v v
while (((scanf_result = scanf("%d", &number)) == 1) && other_condition) {
/* Loop body */
}
if (scanf_result != 1) {
/* The loop terminated because scanf() failed. */
} else {
/* The loop terminated for some other reason. */
}
关于c - while 循环内的 scanf() 错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859708/