求解释~~~~~~~~~~~~~~

過於喧囂的孤獨 2010-11-15 01:20:30
#include <iostream>
#include <exception>
using namespace std;
int main(){
try{
for(int i(0);i!=10;++i){
int j(0);
cout<<"next integer value\t";
cin>>j;
if(not cin) throw exception();
cout<<i<<"\t"<<j<<endl;
}

}
catch(...){
cerr<<"Caught an exception"<<endl;
//return 0;
}
system("pause");
}



我想问的是如果输入一个浮点型数,运行结果有点看不懂!!!
输入: next integer value 3.02

输出: 0 3
next integer value Caught an exception
请按任意键继续...
...全文
105 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2010-11-15
  • 打赏
  • 举报
回复
#include <iostream>
#include <exception>
using namespace std;

int main()
{
try
{
for(int i=0;i!=10;++i)
{
int j=0;
cout<<"next integer value\t"<<flush;
cin>>j;

if(!cin)
{
throw exception("Caught an exception");
}
//cout<<i<<"\t"<<j<<endl;
cout<<j<<endl;
//打印:3,然后进入下一次迭代,读了一个非int的",",cin==false,抛出异常
}
}
catch(exception err)
{
cerr<<err.what()<<endl;
return -1;
}

return 0;
}




haogeai123 2010-11-15
  • 打赏
  • 举报
回复
你的代码风格,
luciferisnotsatan 2010-11-15
  • 打赏
  • 举报
回复
转换了
qingkongxiaoyang 2010-11-15
  • 打赏
  • 举报
回复
这个有什么问题吗?还是我知道的太少了。
j是整形变更啊。虽然为它赋了float型,但是输出仍然会强制转换为整形输出,即3。
应该没问题吧?
龙哥依旧 2010-11-15
  • 打赏
  • 举报
回复
if(not cin)
没见过
就知道cin.fail()
無_1024 2010-11-15
  • 打赏
  • 举报
回复
就是一个异常的理解 多看看书吧
HonryZZ 2010-11-15
  • 打赏
  • 举报
回复
首先输出0
然后cin将从第一个非空白字符开始读取,只到遇到和目标类型不匹配的字符...显然,只读到了3,所以输出3
.02保留在缓冲区,下次再次读取的时候,发现和目标类型不匹配, 输入流关闭,抛出异常...

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧