How to check if a string is a number?

后端 未结 10 2548
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 10:03

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 wh

10条回答
  •  庸人自扰
    2020-11-29 10:38

    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] = '\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;
        }
    }
    

提交回复
热议问题