【C++】C++ 将string字符串类型变量转换为任意类型变量

1. 定义

C++引入了ostringstream、istringstream、stringstream这三个类,要使用他们创建对象就必须包含这个头文件。

  • istringstream类用于执行C++风格的串流的输入操作。
  • ostringstream类用于执行C++风格的串流的输出操作。
  • stringstream类同时可以支持C++风格的串流的输入输出操作。


2. istringstream和stringstream的区别:

istringstream和stringstream都是C++标准库中的类,用于将字符串解析为各种类型的值。

它们的主要区别在于它们的输入源不同

istringstream是从字符串中读取数据,它的输入源是一个字符串。我们可以使用istringstream类的构造函数将一个字符串传给它,然使用>>运算符将字符串解析为各种类型的值

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

// 将std::string字符串类型的变量转换为K模板类型的变量
template<class K>
K getVal(const std::string& str)
{
    K transferVal;
    // 构造函数,从字符串str中读取字符,会自动跳过空格
    // 如果字符串中包含空格,需要使用循环读取while(iss >> transferVal)
    std::istringstream iss(str);
    iss >> transferVal;
    return transferVal;
}

int main()
{
    std::string str = "123";
    int ret = getVal<int>(str);
    std::cout << "string can be transfered to : " << ret << std::endl;
    return 0;
}

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

int main() {
    std::string str = "456";
    int num;
    std::istringstream iss(str);
    iss >> num;
    std::cout << "string can be transfered to : " << num << std::endl;
    return 0;
}


stringstream也可以从字符串中读取数据,但它可以从标准输入、文件等多种输入源中读取数据。我们可以使用stringstream类的构造函数创建一个空的字符串流,然后使用 << 运算符将数据写入字符串流中,或 使用 >> 运算符将数据从字符串流中读取出来。

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

#define PATH "./test"

template<class K>
void getVal()
{
    std::ifstream _file_reader;
    _file_reader.open(PATH);
    
    std::string line_data;

    while(getline(_file_reader, line_data))
    {
        if(line_data.empty()) continue;

        K transferVal;
        std::stringstream ss(line_data);
        ss >> transferVal;
        std::cout << "string can be transfered to : " << transferVal << std::endl;
    }
    _file_reader.close();
}

int main()
{
    getVal1<int>();
    
    return 0;
}
// test文件内容如下:
1
23
34
45

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

int main() {
    // 创建一个空的字符串流,然后使用 << 运算符将数据写入字符串流中
    int num = 123;
    std::stringstream ss;
    ss << num;
    
    std::string str = ss.str();
    std::cout << "The value of str is: " << str << std::endl;
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值