溫馨提示×

streamstring在c++中的應(yīng)用案例分享

c++
小樊
83
2024-09-13 01:55:09
欄目: 編程語言

std::stringstream 是 C++ 標(biāo)準(zhǔn)庫中的一個類,它允許你將字符串視為流對象進(jìn)行操作

  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. 數(shù)值與字符串之間的轉(zhuǎn)換:
#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. 從文件中讀取并解析數(shù)據(jù):
#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++ 中的一些常見應(yīng)用。通過使用 std::stringstream,你可以方便地處理字符串和其他數(shù)據(jù)類型之間的轉(zhuǎn)換,以及對字符串進(jìn)行分割、拼接等操作。

0