简体   繁体   English

c检查整数

[英]c check integer

I'm finding a function to check digit in c, is isdigit only check 0-9 ? 我正在寻找一个函数来检查c中的数字,isdigit仅检查0-9吗? how about 10-99999? 10-99999怎么样?

i have an integer, eg 22, i want to check is it valid? 我有一个整数,例如22,我要检查是否有效?

any ideas? 有任何想法吗? thanks~ 谢谢〜

isdigit et. isdigit al are for checking characters. al用于检查字符。 10-99999 is no longer a single character. 10-99999不再是单个字符。 If you want to check that the string "8382820" is numeric, you have (at least) 3 options: 如果要检查字符串“ 8382820”是否为数字,则(至少)有3个选项:

  • Loop over the string, and run isdigit on each character (failing if one of them isn't) 循环遍历字符串,并在每个字符上运行isdigit (如果其中一个不是,则失败)
  • Use a regular expression ( "^[0-9]+$" should do the trick, but not very practical in C) 使用正则表达式( "^[0-9]+$"应该可以解决问题,但在C语言中不太实用)
  • Use strtol and check that the end pointer is the null terminator. 使用strtol并检查结束指针是否为空终止符。

Here's an idea of how to use strtol: 这是有关如何使用strtol的想法:

char* myString = "9823872";
char* endPtr = NULL;
long int myInt = strtol(myString, &endPtr, 10);

if(endPtr && *endPtr != '\0')
{
    fprintf(stderr, "Sorry, that's not a valid number\n");
    exit(1);
}

There are probably other clever answers involving scanf or atoi, but I'll just leave it at this for now. 可能还有其他涉及scanf或atoi的聪明答案,但我现在就将其保留下来。

The isdigit() function checks one character at a time. isdigit()函数一次检查一个字符。 If you want to check more than one character from a string, loop over the characters in the string and call isdigit() on each one. 如果要检查一个字符串中的多个字符,请遍历字符串中的字符,然后对每个字符调用isdigit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM