streamstring在c++中的应用案例分享

1949idc 2年前 (2024-09-18) 阅读数 287 #编程语言

std::stringstream 是 C++ 标准库中的一个类,它允许你将字符串视为流对象进行操作

  1. 字符串拼接:
#include<iostream>
#include <sstream>
#include<string>

int main() {
    std::stringstream ss;
    ss << "Hello, " << "World!"<< std::ends;
    std::string str = ss.str();
    std::cout<< str<< std::endl;
    return 0;
}
  1. 字符串分割:
#include<iostream>
#include <sstream>
#include<vector>
#include<string>

int main() {
    std::string input = "C++ is a general-purpose programming language.";
    std::istringstream iss(input);
    std::vector<std::string> words;

    std::string word;
    while (iss >> word) {
        words.push_back(word);
    }

    for (const auto& w : words) {
        std::cout << w << std::endl;
    }

    return 0;
}
  1. 数值与字符串之间的转换:
#include<iostream>
#include <sstream>
#include<string>

int main() {
    int num = 42;
    std::stringstream ss;
    ss<< num;
    std::string num_str = ss.str();
    std::cout << "Number as string: "<< num_str<< std::endl;

    double dnum = 3.14;
    ss.str(""); // 清空 stringstream
    ss << dnum;
    std::string dnum_str = ss.str();
    std::cout << "Double as string: " << dnum_str<< std::endl;

    return 0;
}
  1. 从文件中读取并解析数据:
#include<iostream>
#include <fstream>
#include <sstream>
#include<string>
#include<vector>

int main() {
    std::ifstream file("data.txt");
    std::string line;
    std::vector<int> numbers;

    while (std::getline(file, line)) {
        std::istringstream iss(line);
        int num;
        while (iss >> num) {
            numbers.push_back(num);
        }
    }

    for (const auto& n : numbers) {
        std::cout << n << std::endl;
    }

    return 0;
}

这些示例展示了 std::stringstream 在 C++ 中的一些常见应用。通过使用 std::stringstream,你可以方便地处理字符串和其他数据类型之间的转换,以及对字符串进行分割、拼接等操作。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业