Reputation: 13
I am wondering why sscanf does not work correctly. Here is the case
I have a string "1,2,3,#" and I want to extract the data without comma, the code is
int a1,a2,a3;
char s;
string teststr = "1,2,3,#";
sscanf(teststr.c_str(), "%d,%d,%d,%s",&a1,&a2,&a3,&s);
cout << teststr << endl;
cout << a1 << a2 << a3 << s << endl;
the expected output should be 123#
, but the real result I got is 120#
that a3
is always 0.
If I expand to 4 numbers,
int a1,a2,a3,a4;
char s;
string teststr = "1,2,3,4,#";
sscanf(teststr.c_str(), "%d,%d,%d,%d,%s",&a1,&a2,&a3,&a4,&s);
cout << teststr << endl;
cout << a1 << a2 << a3 << a4 << s << endl;
Then the result becomes 1230#
.
It seems like the last int is always 0.
Why will this happen? How to fix it?
Upvotes: 0
Views: 76
Reputation: 16607
sscanf(teststr.c_str(), "%d,%d,%d,%s",&a1,&a2,&a3,&s);
^ passing char variable s to %s (specifier for reading single char is %c not %s)
Instead try this -
sscanf(teststr.c_str(), "%d,%d,%d,%c",&a1,&a2,&a3,&s);
Upvotes: 2