简体   繁体   English

C编程-验证int输入,使其不是字符

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

Need to write a program to take input from a user in the form of an int and validate that what they entered is not a char from az. 需要编写一个程序以int的形式接受用户的输入,并验证他们输入的内容不是来自az的字符。

Is there another way to do this other than: 除了:

if((num != 'a') && (num != 'b') && (num != 'c') && (num != 'd') etc.....) printf("You entered %d", num); if((num!='a')&&(num!='b')&&(num!='c')&&(num!='d')等。。。)printf(“您输入了% d“,数字);

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

You can use the isalpha() function in the "ctype.h" header. 您可以在“ ctype.h”标头中使用isalpha()函数。 It returns true if it is a letter. 如果是字母,则返回true。 So you could do something like: 因此,您可以执行以下操作:

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

Here is a link to the documentation for more information. 这里是文档的链接 ,以获取更多信息。

Rather than trying to work out that it's not a character, work out that it is a digit and discard the rest using the isdigit function from ctype like below. 与其尝试找出它不是一个字符,不如说它是一个数字并使用如下ctype中的isdigit函数丢弃其余字符。

#include <ctype.h>

...

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

But this only works on single characters which is quite useless when you read in strings. 但这仅适用于单个字符,当您读取字符串时这是完全没有用的。 So instead you could instead use the function sscanf. 因此,您可以改为使用sscanf函数。 Like this. 像这样。

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

Another option is to use the atoi function. 另一种选择是使用atoi函数。 But as I recall it doesn't handle errors and I find quite inferior to sscanf. 但是据我所知,它不能处理错误,而且我认为它不如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