簡體   English   中英

如何驗證用戶輸入?

[英]How to validate user input?

在下面編寫的程序中,我如何確保僅輸入整數值? 如果輸入了字符,程序應將其轉換為等效的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);
}

scanf返回成功讀取的項目數,因此您可以檢查以確保它返回的預期數字相同。 例如,

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

注意\\t是一個空格字符, scanf忽略了空格。

只是為了補充詹姆斯所說的話。

不要忘記沖洗標准輸入

#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. 
    }
}

暫無
暫無

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

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