c - while 循环内的 scanf() 错误处理?

标签 c

我是 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/

相关文章:

c - 通过 cURL(或 FTP)将值传递给 C 二进制文件

c - MPI_Bcast 段错误

c - Semmle QL : TaintTracking hasFlow() Problem with Sources that taint their Arguments

c++ - GTK+ 3、C、C++ - 使用库存图片创建按钮

C 从文件中读取 X 个字节,如果需要则填充

c++ - float 到整数的转换

c - 带 header 的 RPN,为什么不起作用?

c - 如何在open mp的for循环中解析 "return 0 or return 1"?

c - 如何使用 Pro*C 连接到数据库?

c - 关于 C 中的 printf 格式字符串