my string starts with abc or abcX, and ends with a number. For example abc0159 or abcX0159. I want to know if i can retrieve the number with sscanf, no matter if 'X' is there or not.
#include <stdio.h>
void main() {
char str1[14] = "abc1234567890";
char str2[15] = "abcX1234567890";
char num[11];
sscanf(str2, "abc%*c%[0-9]", num); //Correct
num[0] = 0;
sscanf(str1, "abc%*c%[0-9]", num); //Removes first digit (wrong).
num[0] = 0;
sscanf(str2, "abc%*[X]%[0-9]", num); //Correct.
num[0] = 0;
sscanf(str1, "abc%*[X]%[0-9]", num); //Gives emty string.
}
Maybe it just doesn't work with sscanf?
Thx.
sscanf(str1, "%*[^0-9]%10s", num);
works with both strings, with *
the value will be read but won't be written into variable, the 10
protects from buffer overflows.
the %*10 helps me. Because now with sscanf(str1, "abc%*10[^0-9]%s", num); "abc" is still obligatory, but X is optional. But it would be even better if the optional letter could be only 'X', and nothing else. I my practical case it is not 'X', but a quatation mark.
Anyway, this is a satisfying solution.
@anonymous yes, it works with quotation marks
"abc\"1234567890"
, it starts scanning on the first digit (10 characters at most)