簡體   English   中英

使用C編程語言中scanf的返回值作為檢查

[英]Using the return value from scanf in the C programming language as a check

你如何使用scanf的返回值來確保它是我得到的雙倍?

double input;

do {  /* do this as long as it not a double */
  printf("Input?");
  scanf("%lf", &input);
} while(scanf("%lf", &input) != 1); /* this will not work */

scanf將返回分配的項目數。 在您的情況下,由於格式字符串僅包含%lf ,因此在您獲得double的情況下,它將完全返回1 您的代碼的問題是您首先在循環內調用scanf ,這將讀取流中的double 然后,在你的while條件下,你再次調用scanf ,但是沒有另一個要讀取的double ,所以scanf什么都不做。

我編寫代碼的方式就像

int no_assigned;
do {
    printf("Input?");
    no_assigned = scanf("%lf", &input);
} while (no_assigned != 1);

額外的變量是因為我感覺像scanf是應該在循環內部的代碼, while不是在while條件下,但這確實是個人偏好; 您可以消除額外的變量並在條件內移動(注意,移動,而不是復制) scanf調用。

編輯:這是使用fgets的版本可能更好:

double input;
char buffer[80];

do {
    printf("Input? ");
    fflush(stdout); // Make sure prompt is shown
    if (fgets(buffer, sizeof buffer, stdin) == NULL)
        break; // Got EOF; TODO: need to recognize this after loop
    // TODO: If input did not fit into buffer, discard until newline
} while (sscanf(buffer, "%lf", &input) != 1);

scanf()和朋友返回成功匹配和分配的輸入項的數量。 沒有與類型相關的信息。 但是既然你已經在轉換字符串中指定了lf ,那么你會得到一個雙倍 - 我想我錯過了你的觀點。

就像邁克爾所說,scanf()返回和整數,表示suceccesfully讀取的元素數量。 據我可以從聯機幫助頁中看到,您無法使用返回值來驗證讀取的內容是否為double。

我想這就是你要做的事情:

double input;

do {  /* do this as long as it not a double */
  printf("Input?");
} while(!scanf("%lf", &input));

scanf()將返回給定/提供的輸入數。 它不會返回任何與數據類型相關的結果。

暫無
暫無

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

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