2017-10-18 201 views
0

如何正確查看在我的scanf函數中讀取了多少個輸入?當我運行下面的代碼不顯示的結果,這是因爲我沒有2個輸入從scanf或其他一些原因 讀到這裏是我的代碼:如何正確驗證在scanf中讀取了多少個輸入

#include <stdio.h> 

int main() 
{ 
float numberOne; 
float numberTwo; 

scanf("%f %f", &numberOne, &numberTwo); 
float result = numberOne + numberTwo; 

int howManyRead = scanf("%f %f", &numberOne, &numberTwo); 

if (howManyRead == 2) 
{ 
    printf("%f", &result); 
} 
else 
{ 
    printf("invalid input"); 
} 
sleep(10); 

} 
+0

https://stackoverflow.com/questions/10469643/value-returned-by-scanf-function-in-c希望這可以幫助。 – Mare70

+2

您是否打算兩次撥打scanf? – user2867342

+0

「在我的scanf函數中讀取了多少輸入?」 - >您希望用戶如何表明輸入已完成?通過輸入文本,然後輸入''\ n''?應該輸入'「123 \ n」'報告只輸入了1個數字還是等待輸入的下一行如「456 \ n」'? – chux

回答

1

你在你的代碼有scanf兩個電話。第一次調用的結果被忽略,而第二次調用的結果被檢查。

當您輸入兩個數字時,第一個scanf會返回2,代碼會忽略。之後,撥打第二個scanf的電話會嘗試讀取兩個附加號碼。

float numberOne, numberTwo; 
if (scanf("%f %f", &numberOne, &numberTwo) == 2) { 
    float result = numberOne + numberTwo; 
    printf("%f", result); 
} else { 
    printf("invalid input"); 
} 
-1

您還沒有以預期的方式使用scanf()返回值:

您可以通過刪除第一次調用scanf解決這個問題。它在那裏可以確定掃描的成敗,並據此作出決定。

你需要做三件事情。

  • 取下兩行

    scanf("%f %f", &numberOne, &numberTwo); 
    float result = numberOne + numberTwo; 
    

    這是因爲,沒有檢查,如果您嘗試使用目標變量的值有可能的情況下,scanf()失敗不確定的。此外,還有重複的scanf()這是錯誤的,不需要的。

  • 在條件塊if (howManyRead == 2)內添加行float result = numberOne + numberTwo;

  • printf通話中移除了&printf("%f", result);

+0

謝謝@melpomene,這使得三點,已經更新。 :) –

+0

downvote的原因? –