while循环中的scanf()错误处理



我是C编程语言的新手,我对如何在while循环中使用scanf()作为条件来捕获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. */
}

使用此逻辑,您无法判断。您将只知道scanf失败,或者其他条件失败。

如果其他条件没有副作用,并且可以在扫描之前执行而不改变程序的行为,则可以编写:

while ( other_condition && 1 == scanf("%d", &number) )
{
    // ...
}
if ( other_condition )
    { /* failed due to other_condition */ }
else
    { /* failed due to scanf or break */ }

或者,您可以显式存储每个扫描结果:

int result = 0;
while ( 1 == (result = scanf("%d", &number)) && other_condition ) 
{
     // ...
}
if ( 1 == result )
    { /* failed due to other_condition or break */ }
else
    { /* failed due to scanf */ }

注:。我使用Yoda Condition,因为在这个场景中我更喜欢这种风格,但你不必这样做。

我认为循环的条件应该是输入:

scanf("%d",number);
while(number==1 && other)

最新更新