Reverse snprintf

Is there any function in C or C ++ to do the opposite of snprintf, so

 char buffer[256]
 snprintf( buffer, 256, "Number:%i", 10);

 // Buffer now contains "Number:10"

 int i;
 inverse_snprintf(buffer,"Number:%i", &i);

 // i now contains 10

I can write a function that itself meets this requirement, but is there already one in the standard libraries?

+4
source share
1 answer

Yes there is sscanf(). It returns the number of tokens successfully mapped to the input, so you can check the return value to see how far it got into the input string.

if (sscanf(buffer, "Number:%i", &i) == 1) {
    /* The number was successfully parsed */
}
+13
source

All Articles