std::stringstream
是 C++ 标准库中的一个类,它允许你将字符串视为流对象进行操作
#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++ 中的一些常见应用。通过使用 std::stringstream
,你可以方便地处理字符串和其他数据类型之间的转换,以及对字符串进行分割、拼接等操作。