Search code examples
cstringatoi

Read first character of string as integer in C


How would I go about reading the first character of this string as an integer?

char *p = argv[1];

Thank you!


Solution

  • Your question is ambiguous. Here are three possible interpretations and their answers.

    1. Every character of a "string" in C is in fact a small integer, which you can retrieve by simply indexing the array.

      int first = p[0];
      
    2. If you know that the first character of the string is a digit and you want its value as a digit, you can take advantage of the fact that the character codes for '0' through '9' are guaranteed to be contiguous and increasing:

      int first_dv = -1;
      if (p[0] >= '0' && p[0] <= '9')
          first_dv = p[0] - '0';
      
    3. If you misspoke, and you actually want to process the whole string as a decimal number, you do that with strtol, or strtoul if the number should never be interpreted as negative:

      char *endp;
      errno = 0;
      long numeric_value = strtol(p, &endp, 10);
      if (endp == p || *endp) {
          fprintf(stderr, "junk after number: %s\n", endp);
      } else if (errno) {
          fprintf(stderr, "%s: invalid number (%s)\n", p, strerror(errno));
      }
      

      These are declared in <stdlib.h>. You do not do this with atoi or sscanf, contra what many other people will tell you: atoi won't tell you if there was junk after the number, and sscanf not only won't tell you that, it is allowed to crash your program on numeric overflow.