std::stringstream
是 C++ 標(biāo)準(zhǔn)庫中的一個類,它允許你將字符串視為流對象進(jìn)行操作
#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;
}
#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;
}
#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;
}
#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)行分割、拼接等操作。