前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++ sstream

c++ sstream

作者头像
全栈程序员站长
发布2022-09-05 10:42:23
4810
发布2022-09-05 10:42:23
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

sstream定义了三个类:istringstream、ostringstream和stringstream分别用来进行流的输入、输出和输入输出操作 由于sstream使用string对象代替字符数组,避免缓冲区溢出的危险;其次,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。相比c库的数据类型转换,sstream更加安全、自动和直接。

1.数据类型转换

代码语言:javascript
复制
#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
using namespace std;
 
int main()
{ 
   
    stringstream sstream;
    string strResult;
    int nValue = 1000;
 
    // 将int类型的值放入输入流中
    sstream << nValue;
    // 从sstream中抽取前面插入的int类型的值,赋给string类型
    sstream >> strResult;
 
    cout << "[cout]strResult is: " << strResult << endl;
    printf("[printf]strResult is: %s\n", strResult.c_str());
 
    return 0;
}

输出 [cout]strResult is: 1000 [printf]strResult is: 1000

2.字符串拼接

  • 注意清空sstream的方式 sstream.str("")clear()适用于进行多次数据类型转换的场景
  • 可以使用str方法,将stringstream类型转换为string类型
  • 可以将多个字符串放入stringstream,实现字符串的拼接目的
代码语言:javascript
复制
#include <string>
#include <sstream>
#include <iostream>
 
using namespace std;
 
int main()
{ 
   
    stringstream sstream;
 
    // 将多个字符串放入 sstream 中
    sstream << "first" << " " << "string,";
    sstream << " second string";
    cout << "strResult is: " << sstream.str() << endl;
 
    // 清空 sstream
    sstream.str("");
    sstream << "third string";
    cout << "After clear, strResult is: " << sstream.str() << endl;
 
    return 0;
}

输出 strResult is: first string, second string After clear, strResult is: third string

3.stringstream的清空

代码语言:javascript
复制
#include <sstream>
#include <iostream>
 
using namespace std;
 
int main()
{ 
   
    stringstream sstream;
    int first, second;
 
    // 插入字符串
    sstream << "456";
    // 转换为int类型
    sstream >> first;
    cout << first << endl;
 
    // 在进行多次类型转换前,必须先运行clear()
    sstream.clear();
 
    // 插入bool值
    sstream << true;
    // 转换为int类型
    sstream >> second;
    cout << second << endl;
 
    return 0;
}

输出 456 1

注意:在本示例涉及的场景下(多次数据类型转换),必须使用 clear() 方法清空 stringstream,不使用 clear() 方法或使用 str(“”) 方法,都不能得到数据类型转换的正确结果。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135966.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年6月4,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.数据类型转换
  • 2.字符串拼接
  • 3.stringstream的清空
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档