C++ 重载输入符 >> 有个坑,不注意无法正确结束while(cin>>x)
2021/11/5 14:10:43
本文主要是介绍C++ 重载输入符 >> 有个坑,不注意无法正确结束while(cin>>x),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
C++允许重载输入输出运算符,对于类的输入,如果不是基本类型,如int,string,可能会出错。
Transaction trsct; while (std::cin >> trsct) { pq.Insert(trsct); if (pq.size() > M) { pq.delMin(); } }
以上代码中Transaction重载了输入符:
std::istream &operator>>(std::istream &is, Transaction &rhs) { is >> rhs.name >> rhs.time >> rhs.money; return is; }
而类的元素为:
std::string name; Date time; double money;
其中Date不是C++的基本类型:需要通过string进行转换:将string 转换为3个int ,int month, int day, int year。
std::istream &operator>>(std::istream &is, Date &item) { std::string date; is >> date; // if (is) // { Date rhs(date); item = rhs; // } return is; }
如果上段代码没有进行 " if(is) " 条件判断,则 “while(cin>>x)” 永远无法正确终止。因为终止时仍然会cin一个空符号给string,然后string不可以转换为int ,结果就卡在 stoi() 这个函数上。
这篇关于C++ 重载输入符 >> 有个坑,不注意无法正确结束while(cin>>x)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain
- 2024-06-19EntBot.ai: AI Website Chatbot for Product Guides and Development Doc
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置