简体   繁体   中英

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.

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. The way many C developers approach this is to store the result in a variable. 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.

If the other condition has no side-effect and can be executed before the scanf without changing the program's behaviour you could write:

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:

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.

I think that the condition of the loop should be the input:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM