C/C++学习笔记十二 Input and Output (I/O)(3)

本文介绍C++中的字符串流类,包括istringstream、ostringstream和stringstream的使用方法。探讨了字符串流类如何进行字符串的读写操作,并演示了如何利用这些类实现字符串与数字之间的相互转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、字符串的流

1、概述

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

        字符串有六个流类:istringstream(派生自istream)、ostringstream(派生自ostream)和stringstream(派生自iostream)用于读写普通字符宽度字符串。 wistringstream、wostringstream 和 wstringstream 用于读取和写入宽字符串。 要使用字符串流,您需要#include sstream 标头。

1、stringstream

        有两种方法可以将数据放入字符串流:

        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() 函数检索缓冲区的结果:

std::stringstream os;
os << "12345 67.89" << '\n';
std::cout << os.str();

//输出
12345 67.89

        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';


//输出
12345 - 67.89

        请注意,>> 运算符遍历字符串——每次连续使用 >> 都会返回流中的下一个可提取值。 另一方面, str() 返回流的整个值,即使 >> 已经在流上使用。

2、字符串和数字之间的转换

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

        首先,让我们看一下将数字转换为字符串:

std::stringstream os;

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

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

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

//输出

12345 67.89

        现在让我们将数字字符串转换为数字:

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';

//输出
12345 67.89

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

        1、使用带有空白 C 样式字符串的 str() 将其设置为空字符串:

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

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

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

        2、使用带有空白 std::string 对象的 str() 将其设置为空字符串:

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

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

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

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

World!

        清除字符串流时,调用 clear() 函数:

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

os.str(""); // erase the buffer
os.clear(); // reset error flags

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

        clear() 重置任何可能已设置的错误标志并将流返回到正常状态。 我们将在下一课中更多地讨论流状态和错误标志。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坐望云起

如果觉得有用,请不吝打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值