您的位置:首页 > 编程语言 > C语言/C++

C++ stringstream类 用法概论

2014-03-25 21:55 197 查看



C++ stringstream 类的用法


功能一:预定的格式将程序中的数据保存在一个string 中





C++ stringstream 类是一种十分有用的类,特别是当我们需要在程序中使用字符串和数字数据的时候。要想在程序中使用 stringstream 类,我们需要在源程序文件中包含头文件include<sstream>。stringstream
对象的使用方法与cout对象的使用方法基本相同。stringstream 类提供的函数,将数字化转化为字符串。

当我们需要按预定的格式将程序中的数据保存在一个string 中的时候,可以先创建一个stringstream 对象,并通过运算符 ”<<“ 将数据传递给 stringstream 对象。(这与通过”<<“ 使用cout 对象的方法相同。)接着,我们可以通过调用stringstream 类的函数str() 将对象所包含的内容赋给一个string对象。在一下的程序中,我们先将数据传递给一个stringstream 对象,然后通过该 stringstream
对象将数值赋给一个string 对象。住:cout能使用的所有ios格式标记也可以在stringstream 对象中使用。

// 如何使用 stringstream
// 对象生成格式化的 string

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
cout << "\n Welcome to the StringStream Demo program.\n";

// 构建一些将在string中出现的数据变量
// PI 精确到小数点后15位
double pi = 3.141592653589793;
float dollar = 1.00;
int dozen = 12;

string text;

// 我们希望tring 的格式如下:
// dozen适12,dollar是$1.00
// 精确到小数点后10为pi是3.141592653589793

// 生成stringstream 对象
stringstream ss;

// 现在像使用cout一样使用ss

ss << " A dozen is "<< dozen << ", a dollar is $ ";
ss.setf(ios::fixed);
ss.precision(2);
ss << dollar << " and \n the value of pi to 10 places is ";
ss.precision(10);
ss << pi << ".";

// 现在将ss中的内容赋给一个string对象
// 使用str()函数

text = ss.str();
cout << "\nHere is our formatted text string:\n" << text << endl;
// 再加入一些信息
ss << "\ There are 2 \"+\" in C++.";
text = ss.str();
cout<< "\nHere is the final string:\n" << text << endl;
return 0;
}


运行结果图:





功能二:实现类型转换




string到 int / double 的转换

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
double  rb;
int     ri;     // 存储结果
string  s;      // 要转化的字符串
stringstream ss;
s = "123.456789";
ss << s;         // 类似 cout
ss >> rb;        // 类似 cin
cout.precision(10);
cout << "string \""<< s << "\" to double object "
<< rb << endl;
s = "654321";
ss.clear();      //清空流
ss << s;
ss >> ri;
cout << "string \""<< s << "\" to int object "
<< ri << endl;
return 0;
}
[align=left][/align]
[align=left]运行结果图:[/align]
[align=center][/align]



[align=center]
[/align]
[align=center]
[/align]

功能三:实现任意类型转换






该功能没多少实际意义,不如static_cast 来的简单。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <class t1="" class="" t2="">

int main()
{
double  sb = 123.456;
int     ri;     // 存储结果
stringstream ss;
ss << sb;
ss >> ri;
cout << ri;
return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息