【问题标题】:parse a string with no spaces with scanf用scanf解析一个没有空格的字符串
【发布时间】:2014-03-04 10:04:50
【问题描述】:

我得到一个这样的字符串:

111222abcd12ae

我想将它拆分为 4 个数值变量,并且我想用 sscanf 在单个代码行中完成它。 这就是我到目前为止所尝试的:

sscanf(mystring, "%3d%3d%4x%4x", &v1, &v2, &v3, &v4)

如你所见

  • v1 应该存储 chars 0 到 2 的十进制值
  • v2 应该存储 chars 3 到 5 的十进制值
  • v3 应该存储 chars 6 到 9 的 hexa 值
  • v4 应该存储 chars 10 到 13 的十六进制值

实际结果:只设置了v4

如何修复我的格式字符串以获得我想要的?

更新

我发现了问题...我已将变量声明为 unsigned short 而不是 int(对于 %d)和 unsigned int(对于 %x),我得到了一个意想不到的结果。

【问题讨论】:

  • printf("%3d %3d %4x %4x", v1, v2, v3, v4); 我得到111 222 abcd 12ae

标签: c string scanf


【解决方案1】:

它对我来说很好,就像你写的那样。

这是一个完整的程序:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *mystring = "111222abcd12ae";
    int v1, v2;
    unsigned int v3, v4;
    const int ret = sscanf(mystring, "%3d%3d%4x%4x", &v1, &v2, &v3, &v4);
    printf("conversion returned %d\n", ret);
    if(ret == 4)
    {
        printf("v1=%d\nv2=%d\nv3=%x\nv4=%x\n", v1, v2, v3, v4);
    }
    return EXIT_SUCCESS;
}

运行它,我得到:

conversion returned 4
v1=111
v2=222
v3=abcd
v4=12ae

您是否在某个嵌入式平台上运行此程序,以便怀疑sscanf() 中的错误/限制?

【讨论】:

  • 该死!我觉得很愚蠢...我声明 unsigned short 而不是 unsigned int 我的 v 变量,我得到了一个意想不到的结果!
  • 啊,这很烦人。对于这种转换/变量不匹配,您应该能够获得编译器警告。另外,请记住 %x 需要 unsigned int。而%d 接受int
猜你喜欢
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多