C++

C++ 知识量:19 - 82 - 316

8.3 string流><

使用istringstream- 8.3.1 -

istringstream是C++标准库中的一个类,它继承自istream,可以用于从字符串中读取数据。要使用istringstream,需要包含头文件<sstream>。

以下是一个简单的示例,演示如何使用istringstream从字符串中读取数据:

#include <iostream>  
#include <sstream>  
using namespace std;  
  
int main() {  
    string str = "123 456 789";  
    istringstream iss(str);  
    int a, b, c;  
    iss >> a >> b >> c;  
    cout << a << " " << b << " " << c << endl; // 输出 123 456 789  
    return 0;  
}

在上面的示例中,首先定义一个字符串str,它包含了一组数字。然后,使用istringstream类创建了一个字符串流iss,并将str传递给它。接着,使用提取运算符>>从字符串流中读取三个整数,并将它们存储在变量a、b和c中。最后,输出这三个整数的值。

注意,在使用istringstream时,需要注意以下几点:

  • 要将字符串传递给istringstream构造函数,或者使用operator=将字符串赋值给istringstream对象。

  • 可以使用提取运算符>>从istringstream中读取数据,但要确保读取的数据类型与变量类型匹配。

  • 在使用完istringstream后,应该及时关闭它,释放资源。

使用ostringstream- 8.3.2 -

ostringstream是C++标准库中的一个类,它继承自ostream,可以用于将数据写入到字符串中。

以下是一个简单的示例,演示如何使用ostringstream将数据写入到字符串中:

#include <iostream>  
#include <sstream>  
using namespace std;  
  
int main() {  
    ostringstream oss;  
    int a = 123;  
    double b = 456.789;  
    oss << "a = " << a << ", b = " << b;  
    string str = oss.str();  
    cout << str << endl; // 输出 a = 123, b = 456.789  
    return 0;  
}

在上面的示例中,首先定义了一个ostringstream对象oss,然后使用插入运算符<<将数据写入到oss中。最后,使用str()函数将oss中的数据转换为字符串,并将其存储在string对象str中。最后,输出str的值。

注意,在使用ostringstream时,需要注意以下几点:

  • 要使用插入运算符<<将数据写入到ostringstream中。

  • 在使用完ostringstream后,应该及时调用str()函数将数据转换为字符串,或者使用seekp(0)函数重置流的位置,以便重复使用ostringstream对象。

  • 在使用完ostringstream后,应该及时关闭它,释放资源。