c++ 使用C语言“sscanf”解析字符串时出现的问题

ajsxfq5m  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(204)

当我想解析一个字符串“INSERT 3 zhaoliu 13“时,我使用了sscanf,但是vscode左边的调试界面告诉我“name”的第一位是'00',也就是说只扫描了“haoliu”,我猜这是缓冲区的问题,但是我该如何修复它。enter image description here下面是我的代码

#include<iostream>
#include"string.h"
using namespace std;

int main(){

    char INSERT[10];
    int id;
    char name[15];
    short strength;
    string instr = "INSERT 3 zhaoliu 13";
    sscanf(instr.c_str(), "%s %d %s %d", INSERT, &id, name, &strength);

}

我试着查了很多资料,但没有找到解决办法

rsaldnfx

rsaldnfx1#

您为其中一个变量指定了错误的类型。strength是一个缩写,因此它应该对应于%hd,而不是%d

sscanf(instr.c_str(), "%s %d %s %hd", INSERT, &id, name, &strength);

将来,我建议编译时打开警告,在g++上使用-Wall时,我会得到一个警告,确切地指出这一点。

so_scanf2.cpp:12:51: warning: format ‘%d’ expects argument of type ‘int*’, but argument 6 has type ‘short int*’ [-Wformat=]
   12 |     int result = sscanf(instr.c_str(), "%s %d %s %d", INSERT, &id, name, &strength);
      |                                                  ~^                      ~~~~~~~~~
      |                                                   |                      |
      |                                                   int*                   short int*
      |                                                  %hd

相关问题