如何检查字符串是否为数字?

我想检查字符串是否是带有此代码的数字。 我必须检查字符串中的所有字符都是整数,但while返回总是isDigit = 1.我不知道为什么如果不起作用。

char tmp[16]; scanf("%s", tmp); int isDigit = 0; int j=0; while(j 57 && tmp[j] < 48) isDigit = 0; else isDigit = 1; j++; } 

忘记ASCII代码检查,使用isdigitisnumber (参见man isnumber )。 第一个函数检查字符是否为0-9,第二个函数还接受各种其他数字字符,具体取决于当前的语言环境。

甚至可能有更好的function来进行检查 – 重要的一点是,这比看起来要复杂一些,因为“数字字符串”的精确定义取决于特定的语言环境和字符串编码。

  if(tmp[j] >= '0' && tmp[j] <= '9') // should do the trick 

在这部分代码中:

 if(tmp[j] > 57 && tmp[j] < 48) isDigit = 0; else isDigit = 1; 

if条件始终为false,导致isDigit始终设置为1 。 你可能想要:

 if(tmp[j] > '9' || tmp[j] < '0') isDigit = 0; else isDigit = 1; 

但。 这可以简化为:

 isDigit = isdigit(tmp[j]); 

但是,你的循环逻辑似乎有点误导:

 int isDigit = 0; int j=0; while(j 

一旦检测到非数字,您应该想要突破循环。 所以while逻辑应该改变:

 while(j 

我需要为我目前正在进行的项目做同样的事情。 以下是我解决问题的方法:

 /* Prompt user for input */ printf("Enter a number: "); /* Read user input */ char input[255]; //Of course, you can choose a different input size fgets(input, sizeof(input), stdin); /* Strip trailing newline */ size_t ln = strlen(input) - 1; if( input[ln] == '\n' ) input[ln] = '\0'; /* Ensure that input is a number */ for( size_t i = 0; i < ln; i++){ if( !isdigit(input[i]) ){ fprintf(stderr, "%c is not a number. Try again.\n", input[i]); getInput(); //Assuming this is the name of the function you are using return; } } 

更明显和简单,线程安全的例子:

 #include  #include  #include  int main(int argc, char **argv) { if (argc < 2){ printf ("Dont' forget to pass arguments!\n"); return(-1); } printf ("You have executed the program : %s\n", argv[0]); for(int i = 1; i < argc; i++){ if(strcmp(argv[i],"--some_definite_parameter") == 0){ printf("You have passed some definite parameter as an argument. And it is \"%s\".\n",argv[i]); } else if(strspn(argv[i], "0123456789") == strlen(argv[i])) { size_t big_digit = 0; sscanf(argv[i], "%zu%*c",&big_digit); printf("Your %d'nd argument contains only digits, and it is a number \"%zu\".\n",i,big_digit); } else if(strspn(argv[i], "0123456789abcdefghijklmnopqrstuvwxyz./") == strlen(argv[i])) { printf("%s - this string might contain digits, small letters and path symbols. It could be used for passing a file name or a path, for example.\n",argv[i]); } else if(strspn(argv[i], "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == strlen(argv[i])) { printf("The string \"%s\" contains only capital letters.\n",argv[i]); } } } 

if X is greater than 57 AND smaller than 48表明您的情况。 X不能同时大于57且小于48。

 if(tmp[j] > 57 && tmp[j] < 48) 

if X is greater than 57 OR smaller than 48

 if(tmp[j] > 57 || tmp[j] < 48)