我有一段代码:
if(string_starts_with(line, "name: ") == 0){
//6th is the first char of the name
char name[30];
int count = 6;
while(line[count] != '\0'){
name[count-6] = line[count];
++count;
}
printf("custom string name: %s", name);
strncpy(p.name, name, 30);
}
else if(string_starts_with(line, "age: ") == 0){
//6th is the first char of the name
printf("age line: %s", line);
short age = 0;
sscanf(line, "%d", age);
printf("custom age: %d\n", age);
}if可以工作,但else if不能工作。示例输出为:
person:
name: great
custom string name: great
age: 6000
age line: age: 6000
custom age: 0我做了很多更改,比如在sscanf函数中使用&age,但都不起作用。
发布于 2015-08-16 23:11:41
如果您想要将一个值存储到short中(为什么?)您需要使用适当的长度修饰符。此外,如果您希望数字位于前缀字符串之后,则需要在前缀字符串之后开始扫描。最后,正如您在传递中提到的,有必要向sscanf提供您想要在其中存储值的变量的地址。
记住检查sscanf的返回值,以确保找到一个数字。
简而言之:
if (sscanf(line + 5, "%hd", &age) != 1) {
/* handle the error */
}如果您在编译时启用了额外警告,则会显示其中几个错误(但不是所有错误)。对于gcc或clang,请始终在编译器选项中使用-Wall。
发布于 2015-08-16 23:12:18
short age = 0;
sscanf(line, "%d", age);age的类型为short,而您使用的格式说明符是%d,这是错误的。
在short中使用%hd -
sscanf(line+5, "%hd",&age);https://stackoverflow.com/questions/32036552
复制相似问题