c++中stringstream的用法
时间: 2023-05-29 07:01:13 浏览: 68
C++ 中有 stringstream 类,用于将字符串转换为各种数据类型,例如整数、浮点数和布尔值等,并支持将这些数据类型转换回字符串。
使用 stringstream 类需要包含头文件 <sstream>。以下是 stringstream 的一些基本用法:
1. 将字符串转换为整数:
```c++
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::string str = "123";
int num = 0;
std::stringstream ss(str);
ss >> num;
std::cout << num << std::endl; // 输出:123
return 0;
}
```
这里将字符串 "123" 转换为整数,并输出转换后的值 123。
2. 将整数转换为字符串:
```c++
#include <sstream>
#include <string>
#include <iostream>
int main() {
int num = 123;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl; // 输出:123
return 0;
}
```
这里将整数 123 转换为字符串,并输出转换后的字符串 "123"。
3. 将字符串转换为浮点数:
```c++
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::string str = "123.45";
float num = 0;
std::stringstream ss(str);
ss >> num;
std::cout << num << std::endl; // 输出:123.45
return 0;
}
```
这里将字符串 "123.45" 转换为浮点数,并输出转换后的值 123.45。
4. 将浮点数转换为字符串:
```c++
#include <sstream>
#include <string>
#include <iostream>
int main() {
float num = 123.45;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl; // 输出:123.45
return 0;
}
```
这里将浮点数 123.45 转换为字符串,并输出转换后的字符串 "123.45"。
除此之外,stringstream 还有许多其他的用法,例如支持多种数据类型的同时转换,或者支持定制化的格式化等,可以参考相关文档进行深入学习。