[英]scanf() error handling inside a while loop?
I'm new to the C programming language and I'm stumped on how I should catch a scanf() error using scanf() as a condition in a while loop. 我是C编程语言的新手,我很困惑如何在while循环中使用scanf()作为条件来捕获scanf()错误。
The code is something like: 代码类似于:
while (scanf("%d", &number == 1) && other_condition)
{
...
}
How could I tell when a integer was not entered so I could print out a relevant error message? 我如何知道何时未输入整数,以便打印出相关的错误消息?
It sounds like you are trying to determine if the scanf()
failed as opposed to the other condition. 听起来您正在尝试确定
scanf()
失败,而不是其他情况。 The way many C developers approach this is to store the result in a variable. 许多C开发人员采用的方法是将结果存储在变量中。 Thankfully, since assignment evaluates to a value, we can actually do this as part of the loop.
幸运的是,由于赋值是一个值,因此我们实际上可以在循环中执行此操作。
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. */
}
Using this logic, you can't tell. 使用这种逻辑,您无法分辨。 You will only know that either scanf failed, or the other condition failed.
您将只知道scanf失败或其他条件失败。
If the other condition has no side-effect and can be executed before the scanf without changing the program's behaviour you could write: 如果其他条件没有副作用,并且可以在scanf之前执行而无需更改程序的行为,则可以编写:
while ( other_condition && 1 == scanf("%d", &number) )
{
// ...
}
if ( other_condition )
{ /* failed due to other_condition */ }
else
{ /* failed due to scanf or break */ }
Alternatively you could explicitly store each scanf result: 或者,您可以显式存储每个scanf结果:
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 */ }
NB. 注意 I use the Yoda Condition as I prefer that style in this scenario, but you don't have to.
在这种情况下,我喜欢使用Yoda Condition,因为我更喜欢这种风格,但是您不必这样做。
I think that the condition of the loop should be the input: 我认为循环的条件应该是输入:
scanf("%d",number);
while(number==1 && other)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.