关于stringstream的用法总结

关于stringstream的用法总结

将整形转化成字符串

#include <iostream>
#include <sstream>

using namespace std;
string i2s(int i, int len = 0)
{
    stringstream ss;
    ss.width(len); //设置宽度
    ss.fill('0'); //填充'0'
    ss << i;
    return ss.str();
}
int main()
{
    int a = 7, b = 3;
    string str = i2s(a, b);
    cout << str << endl;
    return 0;
}

输出结果如下:
在这里插入图片描述

关于stringstream使用的一个例子

题目:输入的第一行有一个数字N代表接下来有N行资料,每一行资料有不固定个数的整数(最多20个,每行最大200个字元),请你写一个程序将每行的总和打印出来。

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    string s;
    stringstream ss;
    int n, i, sum, a;
    cin >> n;
    getline(cin, s);//读取换行,用cin.get()也可以
    for (i = 0; i < n; ++i)
    {
        getline(cin, s);
        ss.clear();
        ss.str(s);
        sum = 0;
        while (1)
        {
            ss >> a;
            if (ss.fail())//如果badfail或failbit被设置,条件才成立(在这里是想要将下一个
            //字符转换成整数,没有成功,所以导致failbit置为1,
            //而eof()表示是到文件尾,若使用的话,用法如下:)
                break;
            sum += a;
        }
        /*while (!ss.eof())//eof()的用法
        {
            ss >> a;
            sum += a;
        }*/
        cout << sum << endl;
    }
    return 0;
}

输出结果如下:
在这里插入图片描述
字符串转换成整形

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    string result = "10000";
    stringstream stream;
    int n = 0;
    stream << result;
    stream >> n;
    cout << n << endl;
    return 0;
}

在这里插入图片描述

重复利用stringstream对象

如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;
在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。

在类型转换中使用模板

你可以轻松地定义函数模板来将一个任意的类型转换到特定的目标类型。例如,需要将各种数字值,如int、long、double等等转换成字符串,要使用以一个string类型和一个任意值t为参数的to_string()函数。to_string()函数将t转换为字符串并写入result中。使用str()成员函数来获取流内部缓冲的一份拷贝:

#include <iostream>
#include <sstream>
using namespace std;
template<class T>
void to_string(string& result, const T& t)
{
    ostringstream oss;//创建一个流
    oss << t; //把值传递入流中
    result = oss.str(); //获取转换后的字符串并将其写入result
}
int main()
{
    string s1, s2, s3;
    to_string(s1, 10.5); //double转换成string
    to_string(s2, 123); //int转换成string
    to_string(s3, true); //bool转换成string
    cout << s1 << endl;
    cout << s2 << endl;
    cout << s3 << endl;
    return 0;
}

结果如下:
在这里插入图片描述
可以更进一步定义一个通用的转换模板,用于任意类型之间的转换。函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型:

#include <iostream>
#include <sstream>
using namespace std;
template<class out_type, class in_value>
out_type convert(const in_value& t)
{
    stringstream stream;
    stream << t;//向流中传值
    out_type result;//这里存储转换结果
    stream >> result;//向result中写入值
    return result;
}
int main()
{
    string salary;
    double d;
    string s = "12.56";
    d = convert<double>(s);//d等于12.56
    salary = convert<string>(9000.0);//salary为"9000"
    cout << d << endl;
    cout << salary << endl;
    return 0;
}

结论

在过去留下来的程序代码和纯粹的C程序中,传统的<stdio.h>形式的转换伴随了我们很长的一段时间。但是,如文中所述,基于stringstream的转换拥有类型安全和不会溢出这样抢眼的特性,使我们有充足得理由抛弃<stdio.h>而使用。库还提供了另外一个特性—可扩展性。你可以通过重载来支持自定义类型间的转换
stringstream通常是用来做数据转换的。
相比c库的转换,它更加安全,自动和直接。

除了基本类型的转换,也支持char *的转换
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    stringstream stream;
    char result[8];
    stream << 8888;//向stream中插入8888
    stream >> result;//抽取stream中的值到result
    cout << result << endl;
    return 0;
}

在这里插入图片描述
< sstream > 库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。一般情况下使用stringstream就足够,因为字符串要频繁的涉及到输入输出。
< sstream > 使用string对象来代替字符数组,这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即便使用了不正确的格式化符也没有危险。
与文件流fstream类似,通过插入器(<<)和析取器(>>)这两个运算符可以直接对stringstream上的数据输入输出,而将stringstream中的全部数据输出则是使用成员函数str(),其有两种形式:
1、void str() //无参形式,用于将stringstream流中的数据以string字符串的形式输出
2、void str (const string& s)//以字符串为参数,用以覆盖stringstream流中的数据
在对同一个stringstream对象重复赋值,就需要先对流使用clear()函数清空流的状态,此时流占用的内存没有改变,会一直增加(stringstream不主动释放内存),若想改变内存(一般是清除内存,减少内存消耗),需要再配合使用str("")清空stringstream的缓存。

关于stringstream中clear()用法的进一步总结

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    stringstream stream;
    int first, second;
    stream << "456";//插入字符串
    stream >> first;//转换成int
    cout << first << endl;
    stream.clear();//清除流
    stream.str("");//清空流缓存
    stream << true;//插入bool值
    stream >> second;//提取出int
    cout << second << endl;
    return 0;
}

在这里插入图片描述

stringstream与fstream

通过重载的<<和>>运算符可以将文件流中的数据输出到C++字符串中,它们之间的媒介是缓冲区streambuf,可由流的成员函数rdbuf()读取。

	string str;
    ifstream in;
    in.open("D:\\C++\\hello.txt");
    //读取文件的缓冲内容到数据流中
    stringstream ss;
    ss << in.rdbuf();
    in.close();//关闭文件
    str = ss.str();//将stringstream流中的数据赋值给string类型字符串
    //const char* p = str.c_str();//将字符串内容转化为C_string类型
    cout << str << endl;
    return 0;

参考博文
string和stringstream用法详解
下面一篇也写的比较好。待有时间进一步总结
C++字符串流stringstream与string知识介绍与用法小结

posted @   笑着的程序员  阅读(43)  评论(0编辑  收藏  举报  
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示