28-4 字符串的流类

到目前为止,你看到的所有 I/O 示例都是向 cout 写入数据或从 cin 读取数据。然而,还有另一组称为字符串流的类,它们允许你使用熟悉的插入 (<<) 和提取 (>>) 运算符来操作字符串。与 istream 和 ostream 类似,字符串流也提供了一个缓冲区来保存数据。但是,与 cin 和 cout 不同,这些流并不连接到 I/O 通道(例如键盘、显示器等)。字符串流的主要用途之一是缓冲输出以便稍后显示,或者逐行处理输入。

字符串流共有六种类型:istringstream(派生自 istream)、ostringstream(派生自 ostream)和 stringstream(派生自 iostream)用于读写标准字符宽度的字符串;wistringstream、wostringstream 和 wstringstream 用于读写宽字符字符串。要使用这些字符串流,需要包含 sstream 头文件。

将数据导入字符串流有两种方法:

1.使用插入运算符(<<):

std::stringstream os {};
os << "en garde!\n"; // insert "en garde!" into the stringstream

2.使用 str(string) 函数设置缓冲区的值:

std::stringstream os {};
os.str("en garde!"); // set the stringstream buffer to "en garde!"

同样,从字符串流中获取数据也有两种方法:

1.使用 str() 函数检索缓冲区的结果:

#include <sstream>
std::stringstream os {};
os << "12345 67.89\n";
std::cout << os.str();

打印出来的内容:

img

2.使用提取(>>)运算符:

std::stringstream os {};
os << "12345 67.89"; // insert a string of numbers into the stream

std::string strValue {};
os >> strValue;

std::string strValue2 {};
os >> strValue2;

// print the numbers separated by a dash
std::cout << strValue << " - " << strValue2 << '\n';

该程序会输出:

img

请注意,>> 运算符会遍历字符串——每次使用 >> 都会返回流中下一个可提取的值。而 str() 函数则会返回流的整个值,即使 >> 运算符已经用于该流中。

字符串和数字之间的转换

因为插入和提取运算符知道如何处理所有基本数据类型,所以我们可以使用它们将字符串转换为数字,反之亦然。

首先,我们来看如何将数字转换为字符串:

std::stringstream os {};

constexpr int nValue { 12345 };
constexpr double dValue { 67.89 };
os << nValue << ' ' << dValue;

std::string strValue1, strValue2;
os >> strValue1 >> strValue2;

std::cout << strValue1 << ' ' << strValue2 << '\n';

这段代码会输出:

img

img

现在让我们把一个数字字符串转换成一个数字:

std::stringstream os {};
os << "12345 67.89"; // insert a string of numbers into the stream
int nValue {};
double dValue {};

os >> nValue >> dValue;

std::cout << nValue << ' ' << dValue << '\n';

该程序会输出:

img

清除字符串流以便重用

有几种方法可以清空字符串流的缓冲区。

1.使用 str() 函数并传入一个空白的 C 风格字符串,将其设置为空字符串:

std::stringstream os {};
os << "Hello ";

os.str(""); // erase the buffer

os << "World!";
std::cout << os.str();

2.使用 str() 函数和一个空的 std::string 对象将其设置为空字符串:

std::stringstream os {};
os << "Hello ";

os.str(std::string{}); // erase the buffer

os << "World!";
std::cout << os.str();

这两个程序都会产生以下结果:

img

img

清除字符串流时,通常最好也调用 clear() 函数:

img

clear() 函数会重置所有可能已设置的错误标志,并将流恢复到正常状态。我们将在下一课中详细讨论流状态和错误标志。

posted @ 2025-12-07 09:46  游翔  阅读(2)  评论(0)    收藏  举报