stringstream的构造函数原形如下:
stringstream::stringstream(string str);
示例代码如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
stringstream ostr("ccc");
ostr.put('d');
ostr.put('e');
ostr<<"fg";
string gstr = ostr.str();
cout<
char a;
ostr>>a;
cout<
system("pause");
}
除此而外,stringstream类的对象我们还常用它进行string与各种内置类型数据之间的转换。
示例代码如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
stringstream sstr;
//--------int转string-----------
int a=100;
string str;
sstr<sstr>>str;
cout<//--------string转char[]--------
sstr.clear();//如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。
string name = "colinguan";
char cname[200];
sstr<sstr>>cname;
cout<system("pause");
}
本文介绍了如何使用C++中的stringstream类来实现字符串与其他基本数据类型之间的转换。文章提供了具体的示例代码,展示了如何将整数转化为字符串,以及如何将字符串转化为字符数组。
3333

被折叠的 条评论
为什么被折叠?



