温馨提示×

c++的stringstream类怎么使用

小亿
103
2023-07-07 14:44:48
栏目: 编程语言

stringstream类是C++标准库中的一个类,用于处理字符串流。它可以将字符串转换为各种类型的数据,并将各种类型的数据转换为字符串。

使用stringstream类需要包含头文件

下面是stringstream类的一些常用方法和示例:

  1. 创建stringstream对象:
#include <sstream> std::stringstream ss; 
  1. 向stringstream对象中写入数据:
ss << "Hello"; // 写入字符串 ss << " " << 123; // 写入整数 ss << " " << 3.14; // 写入浮点数 
  1. 从stringstream对象中读取数据:
std::string str; int num; double dbl; ss >> str; // 读取字符串 ss >> num; // 读取整数 ss >> dbl; // 读取浮点数 
  1. 转换为字符串:
std::string result = ss.str(); 

完整示例:

#include <iostream> #include <sstream> int main() { std::stringstream ss; ss << "Hello"; ss << " " << 123; ss << " " << 3.14; std::string str; int num; double dbl; ss >> str; ss >> num; ss >> dbl; std::cout << "String: " << str << std::endl; std::cout << "Integer: " << num << std::endl; std::cout << "Double: " << dbl << std::endl; std::string result = ss.str(); std::cout << "Result: " << result << std::endl; return 0; } 

上述示例输出:

String: Hello Integer: 123 Double: 3.14 Result: Hello 123 3.14 

希望对你有帮助!

0