std::stringstream
是 C++ 标准库中的一个非常有用的类,它结合了字符串和流的特性,允许你像处理流一样处理字符串。这使得它在字符串格式化、解析和转换等操作中非常方便。(主要是字符串转换成整数,整数转换成字符串)
1. 包含头文件
要使用 std::stringstream
,首先需要包含 <sstream>
头文件:
#include <sstream>
2. 创建 std::stringstream
对象
你可以创建一个空的 std::stringstream
对象,也可以用一个初始字符串来初始化它:
std::stringstream ss; // 创建一个空的 stringstream 对象
std::stringstream ss("Initial string"); // 用初始字符串初始化
3. 写入数据
使用插入操作符 <<
,你可以将各种类型的数据写入 std::stringstream
对象中:
int num = 123;
double pi = 3.14159;
string name = "Alice";
ss << "Number: " << num << ", Pi: " << pi << ", Name: " << name;
//<<作为一个插入符,而且stringstream作为一个流类,在字符流类中插入的任何数据都是可以认为是字符,不管是int,还是double
这行代码将不同类型的变量格式化为一个字符串,并存储在 ss
中。
4. 读取数据
使用提取操作符 >>
,你可以从 std::stringstream
对象中读取数据:
string line;
int age;
double score;
ss << "Alice 30 95.5";
ss >> line >> age >> score;
cout << "Name: " << line << ", Age: " << age << ", Score: " << score << std::endl;
5. 获取字符串内容
使用 str()
方法可以获取 std::stringstream
对象中的字符串内容:
string result = ss.str();
cout << "Result: " << result << endl;
stringstream
类中的 str()
函数会提取流中的所有字符,包括空格。str()
函数返回的是流中当前的所有内容,无论是字母、数字、标点符号还是空格,都会被包含在返回的字符串中。
6. 将整数转换成字符串
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 123;
stringstream ss;
ss << num; // 将整数num写入stringstream对象ss
string str = ss.str(); // 从stringstream对象中获取字符串
return 0;
}
这个的思路是先创建一个stringstream类ss,将整数插入到流中,这样就可以看做是字符串,然后再将这个流用str()函数提取出来.
7.将字符串转换成整数
-
创建一个
std::stringstream
对象。 -
将字符串写入该对象。
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
try {
int num = std::stoi(str);
std::cout << "转换后的整数: " << num << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "无效的输入: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "输入超出范围: " << e.what() << std::endl;
}
return 0;
}
-
cin >>
:从标准输入流读取数据。 -
cout <<
:将数据写入标准输出流。 -
std::stringstream <<
:将数据写入字符串流。 -
std::stringstream >>
:从字符串流中读取数据。