Warm tip: This article is reproduced from serverfault.com, please click

How do i ignore specific character that is not always present, with sscanf?

发布于 2020-12-01 14:15:29

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.

Questioner
anonymous
Viewed
0
David Ranieri 2020-12-01 22:22:10
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.