关于stringstream中clear()用法的进一步总结
关于stringstream中clear()用法的进一步总结
clear()不能清除缓存:
大家看一下:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream stream;
int first, second,third;
stream << "123";//插入字符串
stream >> first;//转换成int
cout << first << " " << stream.str() << endl;
stream.clear();
//stream.str("");//清空流缓存
stream << "456";
stream >> second;//提取出int
cout << second << " " << stream.str() << endl;
stream.clear();
//stream.str("");//清空流缓存
stream << "789";//
stream >> third;//提取出int
cout << third << " " << stream.str() <<endl;
return 0;
}
结果如下:

后面一列数字为缓存,显然没有清除
如果再加上stream,str("")
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream stream;
int first, second,third;
stream << "123";//插入字符串
stream >> first;//转换成int
cout << first << " " << stream.str() << endl;
stream.clear();
stream.str("");//清空流缓存
stream << "456";
stream >> second;//提取出int
cout << second << " " << stream.str() << endl;
stream.clear();
stream.str("");//清空流缓存
stream << "789";//
stream >> third;//提取出int
cout << third << " " << stream.str() <<endl;
return 0;
}
结果如下:

显然清掉了!
那么clear()的作用究竟是什么呢?接下来一起来看一下~~
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream stream;
int first, second,third;
stream << "123";//插入字符串
stream >> first;//转换成int
cout << first << " " << stream.str() << endl;
//stream.clear();
stream.str("");//清空流缓存
stream << "456";
stream >> second;//提取出int
cout << second << " " << stream.str() << endl;
//stream.clear();
stream.str("");//清空流缓存
stream << "789";//
stream >> third;//提取出int
cout << third << " " << stream.str() <<endl;
return 0;
}
现在暂不使用clear(),结果如下:

第二列只有第一行有数字,对此作出的解释如下:
在第一次调用完operator<<和operator>>后,来到了end-of-file的位置,
此时stringstream会为其设置一个eofbit的标记位,标记其为已经到达eof。
查文档得知, 当stringstream设置了eofbit,任何读取eof的操作都会失败,
同时,会设置failbit的标记位,标记为失败状态。所以后面的操作都失败了
clear函数:
原型: void clear (iostate state = goodbit);
标志位一共有4种, goodbit, eofbit, failbit, badbit
clear可以清除掉所有的error state
所以两种清除方式一般结合使用,比较稳妥。
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string line = "1 2 3 4 5";
stringstream s1(line);
string temp;
int toAdd;
stringstream s2;
while (s1 >> temp)//按流输入
{
cout << "temp:" << temp << endl;
s2 << temp;
cout << "s2.str: " << s2.str() << endl;
s2 >> toAdd;
cout << "toAdd:" << toAdd << endl;
s2.str("");
if (s2.eof())
{
s2.clear();
cout << "s2.eof true" << endl;
}
}
return 0;
}
有时间再结合关于stringstream的用法总结
看一下eof()和fail()的差别
【华为OD机试真题】可以转到CSDN相关专栏订阅学习:https://blog.csdn.net/weixin_45541762/article/details/129903356

浙公网安备 33010602011771号