stringstream类是C++标准库中的一个类,用于处理字符串流。它可以将字符串转换为各种类型的数据,并将各种类型的数据转换为字符串。
使用stringstream类需要包含头文件
下面是stringstream类的一些常用方法和示例:
#include <sstream> std::stringstream ss; ss << "Hello"; // 写入字符串 ss << " " << 123; // 写入整数 ss << " " << 3.14; // 写入浮点数 std::string str; int num; double dbl; ss >> str; // 读取字符串 ss >> num; // 读取整数 ss >> dbl; // 读取浮点数 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 希望对你有帮助!