如何在C中检查输入是否为数字?

use*_*316 11 c types

在C的主要功能:

void main(int argc, char **argv)
{
   // do something here
}
Run Code Online (Sandbox Code Playgroud)

In the command line, we will type any number for example 1 or 2 as input, but it will be treated as char array for the parameter of argv, but how to make sure the input is a number, in case people typed hello or c?

Kra*_*mar 20

另一种方法是使用isdigit函数.以下是它的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    printf ("Given input is a number\n");
}
Run Code Online (Sandbox Code Playgroud)

  • 我必须包含`<ctype.h>`. (4认同)

pax*_*blo 13

You can use a function like strtol() which will convert a character array to a long.

It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.

See the following program for an example:

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

int main( int argc, char *argv[]) {
    int i;
    long val;
    char *next;

    // Process each argument given.

    for (i = 1; i < argc; i++) {
        // Get value with failure detection.

        val = strtol (argv[i], &next, 10);

        // Check for empty string and characters left after conversion.

        if ((next == argv[i]) || (*next != '\0')) {
            printf ("'%s' is not valid\n", argv[i]);
        } else {
            printf ("'%s' gives %ld\n", argv[i], val);
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Running this, you can see it in operation:

pax> testprog hello "" 42 12.2 77x

'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid
Run Code Online (Sandbox Code Playgroud)

  • @ user2131316你看过`strtol`的文档吗?您是否知道C文档的存在?你应该先了解C语言*,然后才能在SO上提问. (5认同)

小智 7

使用scanf非常简单,这是一个例子:

if (scanf("%d", &val_a_tester) == 1) {
    ... // it's an integer
}
Run Code Online (Sandbox Code Playgroud)

  • `sscanf` 会更好,但这个特殊的解决方案不会捕捉到像 `77x` 这样的东西。 (3认同)

Mar*_*ius 5

一个自制的解决方案:

bool isNumeric(const char *str) 
{
    while(*str != '\0')
    {
        if(*str < '0' || *str > '9')
            return false;
        str++;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

请注意,此解决方案不应在生产代码中使用,因为它具有严重的局限性。但我喜欢它来理解C-Strings 和 ASCII