std::stringstream

本文介绍了C++标准库中的std::stringstream类,用于字符串的输入输出操作,包括数字转换、从字符串提取数据和数据的字符串输出。通过示例展示了如何使用该类进行符号与数字的解析以及基本的数据操作。
摘要由CSDN通过智能技术生成

std::stringstream 是 C++ 标准库中的一个类,用于对字符串进行输入输出操作,类似于文件流(std::ifstream 和 std::ofstream)。它允许你像使用 std::cin 和 std::cout 一样使用字符串。

std::stringstream 可以将字符串作为输入源,也可以将数据写入到字符串中。它可以在内存中创建一个缓冲区,用于存储输入或输出的数据。

一般来说,std::stringstream 用于以下场景:

  • 将数字转换为字符串。
  • 从字符串中提取数据
  • 将数据以字符串形式进行输出。

使用 std::stringstream 通常需要包含头文件 <sstream>。

在前面的代码示例中,我们使用 std::stringstream 从字符串中提取数字和运算符,然后进行表达式的计算。


用stringstream把符号跟数字分开; 

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
#define int long long
int f(string ss1) 
{
    stringstream ss(ss1);
    vector<int> nums;
    char op;
    int num;
    ss >> num;
    nums.push_back(num);

    while (ss >> op >> num)//自动区分符号跟数字
    {
        if (op == '+') 
        {
            nums.push_back(num);
        }
        else if (op == '-') 
        {
            nums.push_back(-num);
        }
    }
    int sum = 0;
    for (int n : nums) 
    {
        sum += n;
    }
    return sum;
}

signed main() 
{
    int n;
    string ss1;
    cin >> n >> ss1;
    int res = f(ss1);
    cout << res << endl;

    return 0;
}

当需要将数字转换为字符串时,可以使用 std::stringstream 类的实例。以下是一个示例:

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

int main() {
    int number = 123;
    std::stringstream ss;
    ss << number; // 将数字写入 stringstream

    std::string strNumber;
    ss >> strNumber; // 从 stringstream 中提取字符串形式的数字

    std::cout << "String representation of number: " << strNumber << std::endl;

    return 0;
}

当需要从字符串中提取数据时,也可以使用 std::stringstream。以下是一个示例:

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

int main() {
    std::string data = "123 456 789";
    std::stringstream ss(data);

    int num1, num2, num3;
    ss >> num1 >> num2 >> num3; // 从 stringstream 中提取数据

    std::cout << "Extracted numbers: " << num1 << ", " << num2 << ", " << num3 << std::endl;

    return 0;
}

最后,当需要将数据以字符串形式进行输出时,同样可以使用 std::stringstream。以下是一个示例:

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

int main() {
    int num1 = 123, num2 = 456, num3 = 789;
    std::stringstream ss;

    ss << num1 << " " << num2 << " " << num3; // 将数据写入 stringstream

    std::string output = ss.str(); // 获取 stringstream 中的字符串形式数据

    std::cout << "String representation of data: " << output << std::endl;

    return 0;
}

123 456 789

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值