【问题标题】:Sscanf doesn't give me a valueSscanf 没有给我一个价值
【发布时间】:2015-08-16 15:06:53
【问题描述】:

我有这段代码:

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,但是没有任何效果。

【问题讨论】:

  • 我很确定else 也可以。这是不起作用的条件。请提供minimal reproducible example
  • @GilianJoosen 他的意思是line的类型。
  • line 是如何声明的?我们在这里看到了你无法想象的东西。
  • 行是:字符行[200];
  • 请提供完整代码

标签: c arrays string scanf


【解决方案1】:

如果您想将值存储到 short(为什么?)中,您需要使用适当的长度修饰符。此外,如果您希望数字出现在前缀字符串之后,则需要在前缀字符串之后开始扫描。最后,正如您顺便提到的,有必要给sscanf 提供您要在其中存储值的变量的地址

记得检查sscanf 的返回值,确保找到了一个数字。

简而言之:

if (sscanf(line + 5, "%hd", &age) != 1) {
  /* handle the error */
}

如果您在编译时启用了额外警告,则会显示其中几个错误(但不是全部)。对于 gcc 或 clang,请始终在编译器选项中使用 -Wall

【讨论】:

  • @GilianJoosen:您也可以在处理name 时使用它。无需复制line;你可以参考line + 6,虽然最好找到冒号后面的第一个非空白字符,。
【解决方案2】:
short age = 0;
sscanf(line, "%d", age);

ageshort 类型,而您使用的格式说明符是 %d,这是错误的。

使用%hd 代替short-

  sscanf(line+5, "%hd",&age);

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多