C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ std::stringstream

C++中std::stringstream多类型数据拼接和提取用法小结

作者:宗浩多捞

本文主要介绍了C++中std::stringstream多类型数据拼接和提取用法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1、std::stringstream 可以用于不同类型的拼接

在下面示例中,使用std::stringstream将整数、双精度浮点数和字符串连接到一个字符串中,这充分展示了其通用性。 << 运算符可以用于将各种数据类型追加到流中,而不仅仅是字符串。这使得 std::stringstream 成为一个强大的工具,可用于在C++中进行不同类型的拼接和字符串构建。

#include <iostream>
#include <sstream>
#include <string>
int main() 
{
    int intValue = 42;
    double doubleValue = 3.14159;
    std::string stringValue = "Hello, world!";
    std::stringstream ss;
    ss << "Int: " << intValue << ", Double: " << doubleValue << ", String: " << stringValue;
    std::string result = ss.str();
    std::cout << result << std::endl; 
    // 输出 "Int: 42, Double: 3.14159, String: Hello, world!"
    return 0;
}

2、std::stringstream 还可以用于从字符串中提取不同类型的数据到不同的变量中。

以下是一个示例

#include <iostream>
#include <sstream>
#include <string>
int main() {
    std::string data = "42 3.14159 Hello";
    int intValue;
    double doubleValue;
    std::string stringValue;
    std::stringstream ss(data);	
    ss >> intValue >> doubleValue >> stringValue;
    std::cout << "Integer Value: " << intValue << std::endl;
    std::cout << "Double Value: " << doubleValue << std::endl;
    std::cout << "String Value: " << stringValue << std::endl;
    return 0;
}

>> 用于从流中提取数据并进行类型转换,默认分隔符为空格、制表符、换行符: \t\n。这允许你将不同类型的数据从字符串中解析并存储在不同的变量中。

如果想自定义分隔符,那就不能靠>>运算符实现提取了,需要借助std::getline()

到此这篇关于C++中std::stringstream多类型数据拼接和提取用法小结的文章就介绍到这了,更多相关C++ std::stringstream内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文