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

Recently, I need to extract a number from a string, but in a really old C with tools, functions like strtokare not supported. I would prefer sscanf, but I can not understand this. Note that the integer is in a random place (user-defined).

In general, this is what I want as an example:

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

Output:
16
+3
source share
4 answers

A combination of digital filtering and should work sscanf().

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

Extra work needed to overflow numbers.

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; 
}
+1
source

scanf ... , " 16 ". 16 - , .

( , , . , .)

{
char* inputstr = "He is 16 years old.";
int answer = 0;
int params = sscanf (inputstr, "He is %d years old.", &answer);
if (params==1)
    printf ("it worked %d",answer);
else
    printf ("It failed");
}
+2

-, , strtok . C89, , , (, 4.3BSD, 1986 ). sscanf, , , strtok.

, strtok, , , ( sscanf), .

This manual parsing can be quite simple, just iterate over the line until you find a digit, and then collect all consecutive digits when building the number. As soon as you receive a character without numbers, you have your number. Of course, this will only get the first number in the string.

+1
source
#include <stdio.h>

int main() {
    char * string = "He is 16 years old.";
    int age;
    if(sscanf(string, "%*[^0123456789]%d", &age)==1)
        printf("%d\n", age);
    else
        printf("not found\n");
    return 0;
}
+1
source

All Articles