Gil*_*sen 0 c arrays string scanf
我有这段代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
该if作品,但else if不起作用.示例输出是:
person:
name: great
custom string name: great
age: 6000
age line: age: 6000
custom age: 0
Run Code Online (Sandbox Code Playgroud)
我已经改变了很多,比如&age在sscanf函数中使用,但没有任何效果.
如果要将值存储到short(为什么?),则需要使用适当的长度修饰符.此外,如果您希望在前缀字符串后面加上数字,则需要在前缀字符串后面开始扫描.最后,正如您在传递中提到的那样,必须提供要存储值的变量sscanf的地址.
并记得检查返回值,sscanf以确保找到一个数字.
简而言之:
if (sscanf(line + 5, "%hd", &age) != 1) {
/* handle the error */
}
Run Code Online (Sandbox Code Playgroud)
如果您编译时启用了额外警告,则会显示其中一些错误(但不是全部错误).使用gcc或clang,始终-Wall在编译器选项中使用.