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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16644906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:23:42  来源:igfitidea点击:

How to check if a string is a number?

cstring

提问by Astinog

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.

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

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++;
}

回答by zoul

Forget about ASCII code checks, use isdigitor 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.

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

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.

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

回答by Arun

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

回答by Dennis V.R.

More obvious and simple, thread safe example:

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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]);
        }
    }
}

回答by Mitchell Griest

I need to do the same thing for a project I am currently working on. Here is how I solved things:

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

/* 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] = '
if(tmp[j] > 57 && tmp[j] < 48)
  isDigit = 0;
else
  isDigit = 1;
'; /* 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; } }

回答by jxh

In this part of your code:

在这部分代码中:

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

Your ifcondition will always be false, resulting in isDigitalways being set to 1. You are probably wanting:

您的if条件将始终为假,从而导致isDigit始终设置为1。你可能想要:

isDigit = isdigit(tmp[j]);

But. this can be simplified to:

但。这可以简化为:

int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
  isDigit = isdigit(tmp[j]);
  j++;
}

However, the logic of your loop seems kind of misguided:

但是,您的循环逻辑似乎有些误导:

while (isdigit(tmp[j])) ++j;

As tmpis not a constant, it is uncertain whether the compiler will optimize the length calculation out of each iteration.

由于tmp不是常数,因此不确定编译器是否会优化每次迭代的长度计算。

As @andlrc suggests in a comment, you can instead just check for digits, since the terminating NUL will fail the check anyway.

正如@andlrc 在评论中所建议的那样,您可以改为只检查数字,因为无论如何终止 NUL 都会使检查失败。

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

回答by Sani Singh Huttunen

Your condition says if X is greater than 57 AND smaller than 48. Xcannot be both greater than 57 and smaller than 48 at the same time.

你的情况说if X is greater than 57 AND smaller than 48X不能同时大于 57 和小于 48。

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

It should be if X is greater than 57 OR smaller than 48:

它应该是if X is greater than 57 OR smaller than 48

if ( strlen(str) == strlen( itoa(atoi(str)) ) ) {
    //its an integer
}

回答by harvin

#include <stdio.h>
#include <string.h>
char isNumber(char *text)
{
    int j;
    j = strlen(text);
    while(j--)
    {
        if(text[j] > 47 && text[j] < 58)
            continue;

        return 0;
    }
    return 1;
}
int main(){
    char tmp[16];
    scanf("%s", tmp);

    if(isNumber(tmp))
        return printf("is a number\n");

    return printf("is not a number\n");
}

As atoi converts string to number skipping letters other than digits, if there was no other than digits its string length has to be the same as the original. This solution is better than innumber() if the check is for integer.

由于 atoi 将字符串转换为数字以外的数字跳过字母,如果没有其他数字,则其字符串长度必须与原始字符相同。如果检查是整数,则此解决方案比 innumber() 更好。

回答by Marcelo

char isNumber(char *text)
{
    int j;
    j = strlen(text);
    while(j--)
    {
        if(text[j] >= '0' && text[j] <= '9')
            continue;

        return 0;
    }
    return 1;
}

You can also check its stringfied value, which could also work with non Ascii

您还可以检查其字符串化值,该值也适用于非 Ascii

##代码##