无法从字符串中获取第二个整数

时间:2018-04-14 04:39:28

标签: c string

我现在在C学习sscanf,我写了这段代码:

char str[100] ="123asdrZXC456";
char lowercase[100];
char uppercase[100];
int num1;
int num2;
sscanf(str,"%d %[^a-z] %[^A-Z] %d", &num1,lowercase, uppercase,  &num2);
printf("The number is: %d.\n", num1);
printf("The number is: %d.\n", num2);
return 0;

我想从给定的字符串中获取第二个整数“456”。但这是输出:

The number is: 123.
The number is: 0.
Program ended with exit code: 0

我的代码在哪里出错了?任何帮助,将不胜感激!

1 个答案:

答案 0 :(得分:4)

您正在使用%[^a-z],这意味着您想要阅读既不是'a',也不是'b',也不是'c'等字符。抑扬符{{1} }应该用于排除匹配中的以下字符。删除^

^

然后会打印

sscanf(str,"%d %[a-z] %[A-Z] %d", &num1,lowercase, uppercase,  &num2);
  

man scanf

     

<强>转化

     

...

     

The number is: 123. The number is: 456. :匹配指定集合中的非空字符序列   接受的人物; [...] 该集合排除了那些字符   开括号后的第一个字符是旋律([)。 [...]