C++基础教程面向对象(学习笔记(104))

字符串的流类

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

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

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

1)使用insert(<<)运算符:

stringstream os;
os << "en garde!" << endl; // 插入“en garde!”进入stringstream

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

stringstream os;
os.str("en garde!"); // 将stringstream缓冲区设置为“en garde!”

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

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

stringstream os;
os << "12345 67.89" << endl;
cout << os.str();

这打印:

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

stringstream os;
os << "12345 67.89"; // 在流中插入一串数字
 
string strValue;
os >> strValue;
 
string strValue2;
os >> strValue2;
 
// 打印由短划线分隔的数字
cout << strValue << " - " << strValue2 << endl;

该程序打印:

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

字符串和数字之间的转换

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

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

stringstream os;
 
int nValue = 12345;
double dValue = 67.89;
os << nValue << " " << dValue;
 
string strValue1, strValue2;
os >> strValue1 >> strValue2;
cout << strValue1 << " " << strValue2 << endl;

这个片段打印:

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

stringstream os;
os << "12345 67.89"; //在流中插入一串数字
int nValue;
double dValue;
 
os >> nValue >> dValue;
 
cout << nValue << " " << dValue << endl;

该程序打印:

12345 67.89
清除字符串流以供重用

有几种方法可以清空stringstream的缓冲区。

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

stringstream os;
os << "Hello ";
 
os.str(""); // 删除缓冲区
 
os << "World!";
cout << os.str();

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

stringstream os;
os << "Hello ";
 
os.str(std::string()); //删除缓冲区
 
os << "World!";
cout << os.str();

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

World!
清除字符串流时,调用clear()函数通常也是个好主意:

stringstream os;
os << "Hello ";
 
os.str(""); //删除缓冲区
os.clear(); //重置错误标志
 
os << "World!";
cout << os.str();

clear()重置,可能已设置的任何错误标志,并将流返回到ok状态。我们将在下一课中详细讨论流状态和错误标志。

猜你喜欢

转载自blog.csdn.net/qq_41879485/article/details/84921126