How to extract an integer from a string with a mixed alphabet, punctuation and integers in C?

I have a line that looks like "AGE: 83". I want to take the integer "83" from this line, and I know that I should use the "sscanf" function. However, there is no space between this line. How can i do this?

+4
source share
1 answer

Use this:

const char *str = "AGE:83";
int age;

sscanf(str, "%*[^0-9]%d", &age);

This format skips any digits and parses the integer after that.

Please note that it will not work if there are no digits in front of the number. To handle the case where a number may be at the beginning of a line, first try a direct match:

if (sscanf(str, "%d", &age) != 1
&&  sscanf(str, "%*[^0-9]%d", &age) != 1) {
    // no number found;
    return 1;
}
// age was correctly extracted from `str`

, , '-' ( "%*[^0-9-]%d")

atoi() strtol():

age = atoi(str + strcspn(str, "0123456789"));

, , , AGE:, :

age = atoi(str + 4);

undefined, 4 , .

+6

Source: https://habr.com/ru/post/1648898/


All Articles