如何使用scanf的返回值來確保它是我得到的雙倍數?使用C編程語言中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的返回值來確保它是我得到的雙倍數?使用C編程語言中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
條件,但這實際上是個人偏好;您可以消除額外的變量,並在條件內移動(注意,移動,不復制)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()將返回給定/提供的輸入數量。它不會返回任何與數據類型相關的結果。
就像邁克爾說的那樣,scanf()返回和表示可以讀取的元素數的整數。據我可以看到從聯機幫助頁你不能使用返回值來驗證是否讀取是一個雙重或不。
我想這是你想要做什麼:
double input;
do { /* do this as long as it not a double */
printf("Input?");
} while(!scanf("%lf", &input));
+1說這是個人喜好。我更喜歡它自己在循環內,但我要判斷誰呢? – 2009-12-23 10:07:34
我這樣做,但我必須fflush(stdin);在scanf之後還是會永久循環(如果我把它放在while狀態)? – 2009-12-23 12:11:37
不,不要做'fflush(stdin);'因爲這不能保證你做它認爲的事情。 'scanf'確實會在輸入中留下換行符。如果將來使用'scanf',這應該不會影響,因爲'scanf'會跳過空格,但如果您使用其他輸入函數,則需要在此之前刪除換行符。實際上,更好的方法可能是在'while'循環中用'fgets'輸入一行,然後在該行上使用'sscanf',就像您現在使用'scanf'一樣。 – JaakkoK 2009-12-23 12:25:13