打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
stringstream的用法

    博客分类:
  • C++
stringstream通常是用来做数据转换的。相比c库的转换,它更加安全,自动和直接。

例子一:基本数据类型转换例子 int转string



#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::stringstream stream;
    std::string result;
    int i = 1000;
    stream << i; //将int输入流
    stream >> result; //从stream中抽取前面插入的int值
    std::cout << result << std::endl; // print the string "1000"
}




运行结果:print the string "1000"






例子二:除了基本类型的转换,也支持char *的转换。



#include <sstream>
#include <iostream>

int main()
{
    std::stringstream stream;
    char result[8] ;
    stream << 8888; //向stream中插入8888
    stream >> result; //抽取stream中的值到result
    std::cout << result << std::endl; // 屏幕显示 "8888"
}

屏幕显示 "8888"





例子三:再进行多次转换的时候,必须调用stringstream的成员函数clear().



#include <sstream>
#include <iostream>
int main()
{
    std::stringstream stream;
    int first, second;
    stream<< "456"; //插入字符串
    stream >> first; //转换成int
    std::cout << first << std::endl;
    stream.clear(); //在进行多次转换前,必须清除stream
    stream << true; //插入bool值
    stream >> second; //提取出int
    std::cout << second << std::endl;
}

运行clear的结果
456
1
没有运行clear的结果
456
8800090900

顺便介绍用stringstream配合string进行格式化的方法有点像CString.Format:
    stringstream ss;
    ss << 100 << endl;;
    ss << "fuck" << endl;
    string s( ( istreambuf_iterator< char >( ss ) ), istreambuf_iterator< char >() );
    cout << s;
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
string和stringstream用法总结
istringstream、ostringstream、stringstream 类介绍 .
stringstream的基本用法
C++中的数据类型转换方法总结
C++字符串分割
c++数字和字符串的转换
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服