簡體   English   中英

在while循環內scanf()錯誤處理?

[英]scanf() error handling inside a while loop?

我是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失敗或其他條件失敗。

如果其他條件沒有副作用,並且可以在scanf之前執行而無需更改程序的行為,則可以編寫:

while ( other_condition && 1 == scanf("%d", &number) )
{
    // ...
}

if ( other_condition )
    { /* failed due to other_condition */ }
else
    { /* failed due to scanf or break */ }

或者,您可以顯式存儲每個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 */ }

注意 在這種情況下,我喜歡使用Yoda Condition,因為我更喜歡這種風格,但是您不必這樣做。

我認為循環的條件應該是輸入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM