【c++】字符串流输出恢复状态问题
2023-09-27 14:25:21 时间
缘起
#include <iostream> #include <sstream> using namespace std; int main() { istringstream iss; string str1, str2, str3, str4, str5, str6; iss.str("I love you"); iss >> str1 >> str2 >> str3; cout << str1 << " " << str2 << " "<< str3 << endl; iss.str("I hate you"); iss >> str4 >> str5 >> str6; cout << str4 << " " << str5 << " "<< str6 << endl; }
期待输出
可以结果是
问题
没有输出“I hate you"。究竟是什么原因导致 流没有输出到字符串中?
一番折腾知道,此时流的eof为1(已经达到结束符),此时必须用函数clear()把所有的状态值设为有效状态值。经过修改程序如下:
#include <iostream> #include <sstream> using namespace std; int main() { istringstream iss; string str1, str2, str3, str4, str5, str6; iss.str("I love you"); cout << "before" << iss.str() << endl; iss >> str1 >> str2 >> str3; cout << str1 << " " << str2 << " "<< str3 << endl; cout << "eofbit:" << iss.eof() << endl; iss.clear(); cout << "eofbit:" << iss.eof() << endl; iss.str("I hate you"); cout << "after:" << iss.str() << endl; iss >> str4 >> str5 >> str6; cout << str4 << " " << str5 << " "<< str6 << endl; }
正确结果
程序用到知识
相关文章
- C/C++数据结构(七) —— Tree的前世今生
- C++-std:tuple元组的基本用法
- Lua 跟 C++ 的交互
- 【转载】c++类的实例化与拷贝
- 从零开始学C++之IO流类库(二):文件流(fstream, ifstream, ofstream)的打开关闭、流状态
- 在Eclipse中实现C++ 11的完整支持
- 7z系列之一:7zip SDK中C++模块的编译
- C#调用C++ dll及dll编写方法
- 设计模式C++学习笔记之十九(State状态模式)
- C/C++跨平台程序注意
- Linux系统下C++开发工具-远程终端软件使用
- C++STL:deque的介绍 | 对其内存布局进行图解
- c++:c和c++区别
- C++必知必会:统一的类成员初始化语法与std::initializer_list<T>