简体   繁体   中英

How to check input in command line is integer in C?

I want the code to check input in command line is integer. ie 10b is not valid. I tried isdigit() but is not working? Thanks in advance.

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>

int main(int argc, string argv[])
{
   if (argc == 2)
   {
       int key = atoi(argv[1]);

       if (isdigit(key))
       {
          printf("Success\n\%i\n", key);
          exit(0);
       }

    }
  printf("Usage: ./caesar key\n");
  return 1;
}

Function isDigit checks if a single character is a digit, ie in the range between '0'..'9' . To check if a string is a number, I'd suggest to use function strtol .

long strtol(const char *str, char **str_end, int base ) converts a string str to an integral number and also sets the pointer str_end to the first character that took not part in the conversion any more. If you require that no characters must follow your number, then str_end must point to the string's end, ie to string termination character '\\0' :

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

int isNumber(const char* str) {

    if (!str || *str=='\0') {  // NULL str or empty str: not a number
        return 0;
    }

    char* endOfNum;
    strtol(str,&endOfNum,10);

    if (*endOfNum == '\0') { // string is at its end; everything in it was a valid part of the number
        return 1;
    } else {
        return 0;  // something that is not part of a number followed.
    }

}

int main() {
    const char* vals[] = {
        "10b",
        "-123",
        "134 ",
        "   345",
        "",
        NULL
    };

    for (int i=0; vals[i]; i++) {
        printf("testing '%s': %d\n", vals[i], isNumber(vals[i]));
    }
}

Output:

testing '10b': 0
testing '-123': 1
testing '134 ': 0
testing '   345': 1
testing '': 0

Adapt the meaning of corner cases like empty strings or NULL-strings to your needs.

My first thought would be to use something like:

int inputvalue = 0;
if (sscanf(argv[i], "%d", &inputvalue) == 1)
{
    // it's ok....
}
else
{
    // not an integer!
}

or something like that. See http://www.cplusplus.com/reference/cstdio/sscanf/

The isdigit function checks whether a single character represents a single digit. (numbers − 0 1 2 3 4 5 6 7 8 9).

In order to check if a string is an integer you could use a function like that. It will

bool isNumber(char number[])
{
    int i = 0;
    // only if you need to handle negative numbers 
    if (number[0] == '-')
        i = 1;
    for (; number[i] != 0; i++)
    {
        if (!isdigit(number[i]))
            return false;
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM