例如,给定文件中的这行文本
Today: Wed @2p,@3p,5
我怎么才能用sscanf得到“@2p”?现在我正在使用以下代码:
char 1st[3];
char 2nd[3];
int num;
sscanf(str,"%*[^:]%*[^\t]%s,%s,%d", 1st, 2nd, &num);
printf("1st = %s\n", 1st);
printf("2nd = %s\n", 2nd);
printf("num = %s\n", &num);
结果是
1st = Wed
2nd = 'empty characters'
num = 'empty characters'Wed
我在这里会做错什么?
最佳答案
以下操作失败,因为"%*[^:]"
扫描"Today"
,然后"%*[^\t]"
扫描":"
,"%s"
扫描并不保存"\t"
,继续扫描并将"Wed"
保存到一个太小导致未定义行为的数组中。
sscanf("Today:\tWed @2p,@3p,5", "%*[^:]%*[^\t]%s,%s,%d", 1st, 2nd, &num);
下面的失败原因是
"%*[^:]"
扫描"Today"
,然后"%*[^\t]"
扫描": Wed @2p,@3p,5"
,没有为"%s"
留下任何内容。它也不会检查sscanf()
的结果。总是检查结果以确保有效的结果。sscanf("Today: Wed @2p,@3p,5", "%*[^:]%*[^\t]%s,%s,%d", 1st, 2nd, &num);
而且
"@2p"
不能放入char [3]
数组。需要空字符的空间。决定什么是可接受的字符:扫描集和最大字符数。检查结果
#define Word_Max 3
#define Prefix "%*[^@]"
#define ScanSet "%3[A-Za-z0-9@]"
char *str = "Today: Wed @2p,@3p,5";
char word[2][Word_Max + 1];
int num;
if (3 == sscanf(str, Prefix ScanSet "," ScanSet ",%d", word[0], word[1], &num)) {
printf("'%s' '%s' %d\n", word[0], word[1], num);
} else {
puts("Fail");
}
输出
'@2p' '@3p' 5