Search code examples
cstringnumbersoutputscanf

C-Language: How to get number from string via sscanf?


Recently I have need to extract a number from a string, but on really old C with means functions like strtok are not supported. I would prefer sscanf, but i can't understand it. Note that the integer is in random place (user-defined).

In general thats what i want to happan as an example:

Input:
char * string = "He is 16 years old.";

Output:
16

Solution

  • A combination of digit filtering and sscanf() should work.

    int GetNumber(const char *str) {
      while (!(*str >= '0' && *str <= '9') && (*str != '-') && (*str != '+') && *str) str++;
      int number;
      if (sscanf(str, "%d", &number) == 1) {
        return number;
      }
      // No int found
      return -1; 
    }
    

    Additional work needed for numbers that overflow.

    A slower, but pedantic method follows

    int GetNumber2(const char *str) {
      while (*str) {
        int number;
        if (sscanf(str, "%d", &number) == 1) {
          return number;
        }
        str++;
      } 
      // No int found
      return -1; 
    }