簡體   English   中英

我的“ scanf”循環沒有停止; 當條件不起作用時

[英]My 'scanf' loop doesn't stop; while condition is not working

我應該做這個練習:用C編寫一個程序在屏幕上打印一個頻率圖表。 輸入和輸出:程序將三元組序列(數字,頻率,字符)作為輸入。 對於每個序列,它應打印一個斜線,生成一個圖形,如下例所示。

輸入示例

(5,12, -) (4,17, -) (2,1, -) (1,19, +)

該程序應打印

  5 | ------------ 12
  4 | ----------------- 17
  2 | -
  1 | +++++++++++++++++++ 19

我意識到,如果我在scanf函數中的句子之前放置一個空格,它會很好地工作,但是該程序並不會在預期的時候結束

int main()
{
    int x, b, i, u;
    char n;

    do{
        u = scanf(" (%d,%d,%c)", &x, &b, &n);
        printf("%d |", x);
        for (i = 0; i < b; i++){
            printf("%c", n);
        }
        printf(" %d\n", b);
    }while(u == 3);
}

可以預期的是,當scanf不能讀取它應該讀取的3件事時,while循環結束並且程序結束。 但是,當發生這種情況時,他仍在等待新的輸入。 我該如何解決?

只需檢查u的返回值,然后使用if條件。 該shold停止while循環並退出程序

int main()
{
int x, b, i, u;
char n;


do{
    u = scanf(" (%d,%d,%c)", &x, &b, &n);
    if(u == 3){
        printf("%d |", x);
        for (i = 0; i < b; i++){
            printf("%c", n);
        }
        printf(" %d\n", b);
    }

}while(u == 3);

暫無
暫無

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

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