foips
foips

Reputation: 641

Inverse of snprintf

Is there any function in C or C++ to perform the inverse of an snprintf, such that

 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 meets this requirement myself, but is there already one within the standard libraries?

Upvotes: 5

Views: 4111

Answers (2)

RaymondY
RaymondY

Reputation: 35

In addition to sscanf(), if you are only going to scan numbers, you can safely scan numeric values using the strto*() functions: strtol(), strtoll(), strtoul(), strtoull(), strtof(), strtod(), strtold(). You can also use atoi(), atol() and atoll(), but note that these functions return 0 if the string is not an integer that can be converted.

Upvotes: 0

cdhowie
cdhowie

Reputation: 169143

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

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

Upvotes: 16

Related Questions