Home > Mobile >  Problems when I use C language "sscanf" to parse a string
Problems when I use C language "sscanf" to parse a string

Time:12-15

When I wanted to parse a string "INSERT 3 zhaoliu 13", I used sscanf, but the debugging interface on the left of vscode told me that the first digit of "name" was '00', that is, only "haoliu" was scanned, I'm guessing it's a buffer issue, but how do I fix it. enter image description here Below is my code

#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);


}

I tried to check a lot of information, but couldn't find a solution

CodePudding user response:

You've specified the wrong type for one of your variables. strength is a short so it should correspond to %hd, not to %d.

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

In the future, I recommend compiling with warnings turned on. With -Wall on g , I get a warning indicating exactly this.

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

  •  Tags:  
  • c
  • Related