Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading