c++ - 从 sscanf 中提取数据

标签 c++ c c++11

我想知道为什么 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/

相关文章:

c++ - 层次结构中的反向可变参数模板参数

c++ - 友元、模板、命名空间

c++ - 使用或不使用 boost::bind() 创建一个 boost::thread

c - 为什么 symlink() 总是打印 symlink failed?

c - 如何在外部程序中使用通过内存扫描器发现的数据?

c - 为什么for循环没有被执行?(线性搜索)

c++ - 为什么 emplace_back 调用析构函数?

c++ - 试图解释 Windows 操作系统上的用户 session 状态

c++ - 将 std::vector 传递给构造函数并移动语义

使用默认构造函数生成的c++移动构造函数