繁体   English   中英

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

[英]C++ using std::sscanf and std::string

我想从字符串中“提取”信息。 该字符串始终采用int int char格式。

我在此上花了很长时间,检查了我发现的该网站和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()的文档,您就可以自己回答问题。

如果您确实坚持使用sscanf() ,则需要传递num1num2num3的地址,而不是它们的值。

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

与尝试使用C中不推荐使用的函数相比,使用stringstream (在标准头文件<sstream>声明)会更好。

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

您需要操作员的地址,即

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM