我如何使用 sscanf 忽略并不总是存在的特定字符?

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

我的字符串以 abc 或 abcX 开头,以数字结尾。 例如 abc0159 或 abcX0159。 我想知道我是否可以用 sscanf 检索号码,无论 'X' 是否存在。

#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.
}

也许它不适用于 sscanf?

谢谢。

sscanf(str1, "%*[^0-9]%10s", num);

适用于两个字符串,* 值将被读取但不会写入变量,10 防止缓冲区溢出。