2010-08-11 42 views
1

在下面寫的程序中,我如何確保只輸入整數值? 如果輸入字符,程序應該將其轉換爲其ASCII碼,然後添加它們並將輸出顯示爲數字。 請幫我......如何驗證用戶輸入?

#include<stdio.h> 
int main(int argc, char **argv) 
{ 
int a,b,c; 
printf("enter two numbers:-"); 
scanf("%d \t %d",&a,&b); 
c=a+b; 
printf("addition of numbers= %d",c); 
} 
+0

對於記錄,詞彙量不是很充足,在這裏:這通常不會被視爲參數,但作爲*輸入*。你可能想編輯你的問題的標題。 – 2010-08-11 14:30:23

回答

2

scanf返回它成功地讀取,所以你可以檢查,以確保它返回您所期望的相同數量的項目數。例如,

if (scanf("%d \t %d", &a, &b) != 2) 
{ 
    // handle error 
} 

注意\t是一個空白字符,和空格被忽略scanf

+0

謝謝你對我有用的信息 – 2010-08-11 13:43:53

1

只是爲了增加詹姆斯所說的。

不要忘記沖洗標準輸入

#include<stdio.h> 
int main(int argc, char **argv) 
{ 
int a,b,c; 

printf("enter two numbers:-"); 
if(scanf("%d \t %d",&a,&b) == 2) 
{ 
    c=a+b; 
    printf("addition of numbers= %d",c); 
} 
else { 
     printf("please enter a valid input"); 
     getchar(); // the getchar will clear the stdin otherwise next time you go do 
        // a scanf it might not work. 
    } 
} 
+0

謝謝你幫我多了.......... – 2010-08-13 13:03:56

+0

不客氣 – jramirez 2010-08-16 15:47:28