zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

C++笔记学习 and input 十二 output
2023-09-14 09:15:03 时间

一、字符串的流

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