簡體   English   中英

C編程-驗證int輸入,使其不是字符

[英]C programming - validating int input so it isn't a character

需要編寫一個程序以int的形式接受用戶的輸入,並驗證他們輸入的內容不是來自az的字符。

除了:

if((num!='a')&&(num!='b')&&(num!='c')&&(num!='d')等。。。)printf(“您輸入了% d“,數字);

是的,使用ctype.h頭文件中提供的isdigit()函數

您可以在“ ctype.h”標頭中使用isalpha()函數。 如果是字母,則返回true。 因此,您可以執行以下操作:

if ( !isalpha() )
{
    // Do whatever
}

這里是文檔的鏈接 ,以獲取更多信息。

與其嘗試找出它不是一個字符,不如說它是一個數字並使用如下ctype中的isdigit函數丟棄其余字符。

#include <ctype.h>

...

if (isdigit(num)) {
  printf("You entered %d\n", num);
}

但這僅適用於單個字符,當您讀取字符串時這是完全沒有用的。 因此,您可以改為使用sscanf函數。 像這樣。

int num;
if (sscanf(numstr, "%d", &num)){
  printf("You entered %d\n", num);
} else {
  printf("Invalid input '%s'\n", numstr);
}

另一種選擇是使用atoi函數。 但是據我所知,它不能處理錯誤,而且我認為它不如sscanf。

#include <stdio.h>
int main()
{
    char c;
    printf("Enter a character: ");
    scanf("%c",&c);
    if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
       printf("%c is an alphabet.",c);
    else
       printf("%c is not an alphabet.",c);
    return 0;
}

暫無
暫無

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

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