我想知道为什么 sscanf 不能正常工作。情况是这样的
我有一个字符串“1,2,3,#”,我想提取不带逗号的数据,代码是
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;
预期的输出应该是123#
,但我得到的真实结果是120#
,即a3
总是0。
如果我扩展到 4 个数字,
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;
那么结果就变成了1230#
。
似乎最后一个 int 总是 0。
为什么会这样?如何解决?
最佳答案
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)
试试这个 -
sscanf(teststr.c_str(), "%d,%d,%d,%c",&a1,&a2,&a3,&s);
关于c++ - 从 sscanf 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676091/