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

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

(c - How do i ignore specific character that is not always present, with sscanf?)

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

我的字符串以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?

谢谢。

Questioner
anonymous
Viewed
11
David Ranieri 2020-12-01 22:22:10
sscanf(str1, "%*[^0-9]%10s", num);

对两个字符串均有效,*将读取值但不会将其写入变量,从而10防止缓冲区溢出。