且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否一个字符串是多少?

更新时间:2023-11-28 23:47:10

忘记ASCII code盘,使用 ISDIGIT ISNUMBER (见 男人ISNUMBER )。第一个功能检查字符是否为0-9,第二个也接受其他各种字符数取决于当前的语言环境。

有可能甚至更好的功能做检查 - 重要的教训是,这是一个有点复杂得多,它看起来,因为数字串的precise定义依赖于特定的语言环境和字符串编码。

I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don't know why that if doesn't work.

char tmp[16];
scanf("%s", tmp);

int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
  if(tmp[j] > 57 && tmp[j] < 48)
    isDigit = 0;
  else
    isDigit = 1;
  j++;
}

Forget about ASCII code checks, use isdigit or isnumber (see man isnumber). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.

There may even be better functions to do the check – the important lesson is that this is a bit more complex than it looks, because the precise definition of a "number string" depends on the particular locale and the string encoding.