簡體   English   中英

scanf無法在c中正確讀取輸入

[英]scanf not reading input properly in c

這是我的代碼:

#include<stdio.h>
main()
{
    int a,b;
    float f;
    scanf("%2d%3d%4f",&a,&b,&f);
    printf("%d %d %f",a,b,f);
    return 0;
}

我輸入時的程序輸出。(僅點):

.
0 1 0.000000

如果在解析時scanf無法提取3個數字,則各個變量保持不變,即在您的情況下未初始化。 訪問未初始化的變量會產生未定義的行為,這可能是不確定的輸出,但理論上也可能根本沒有輸出。

因此,您的代碼中有兩件事:第一,初始化變量;第二,初始化變量。 其次,檢查scanf的返回值,該值代表已成功讀取並分配的項目數:

#include<stdio.h>
main()
{
    int a=0,b=0;
    float f=0.0;
    int nrOfItemsRead = scanf("%2d%3d%4f",&a,&b,&f);
    if (nrOfItemsRead == 3) {
      printf("%d %d %f",a,b,f);
    }
    else {
      printf("wrong input.");
    }
    return 0;
}

輸入輸出:

12 34 12.5
12 34 12.500000

.
wrong input.

暫無
暫無

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

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