C++ 使用 std::sscanf 和 std::string

C++ using std::sscanf and std::string

我想要 "extract" 来自字符串的信息。字符串始终采用 int int char.

格式

我在这上面花了很多时间,检查了 "every" 这个网站的例子,google 我发现了,但无济于事。一些示例已编译,但崩溃了(没有溢出。)

这是当前的,它编译但崩溃。

// Data                    
string str = "53 25 S";
int num1;
int num2;
char type3;

// Read values                                  
sscanf(str.c_str(),"%i %i %c",num1,num2,type3);

您需要运营商的地址,即

sscanf(str.c_str(),"%i %i %c",&num1,&num2,&type3);

简单阅读 sscanf() 的任何基本文本和文档,您就可以自己回答这个问题。

如果你真的坚持要用sscanf(),那么需要传递num1num2num3的地址,而不是它们的值

sscanf(str.c_str(),"%i %i %c",&num1,&num2,&type3);

最好使用 stringstream(在标准头文件 <sstream> 中声明),而不是尝试使用 C 中已弃用的函数。

std::istringstream some_stream(str);
some_stream >> num1 >> num2 >> type3;