C++ stringstream类 用法概论
2014-03-25 21:55
197 查看
C++ stringstream 类的用法
功能一:预定的格式将程序中的数据保存在一个string 中
对象的使用方法与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]
功能三:实现任意类型转换
#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; }
相关文章推荐
- zlib用法简单说明
- 批处理中的SET的基本用法
- Delphi学习手记——pos 函数用法
- over用法
- vc 热键、组合键的用法 MFC c++ hotkey WM_HOTKEY
- FileSystemWatcher 基础用法
- HttpURLConnection用法详解
- assert()函数用法总结
- Microsoft.XMLHTTP基本用法
- Eclipse用法和技巧一:还原视图和编辑器
- static用法详解
- Jquery基本用法总结
- Linux下cut命令用法
- Java中的split函数的用法
- C++const关键字用法
- Visual C++2010中CMFCPropertySheet的用法
- git的用法03
- MFC总结之CListCtrl用法及技巧(二)
- SqlServer中quotename用法与实例
- LinkedList 基本用法