csjw1992 2016-12-13 04:44 采纳率: 0%
浏览 2113

c++中while(!(cin >> a))无限循环的问题

不管用goto还是while都是无限循环,求问这是为什么
代码如下:

 #include <iostream>
#include <stdexcept>
#include <exception>
using namespace::std;
int main(){
    int a, result{ 1 };
    cout << "input a number:" << endl;
// retry:
    // try{
        // cin >> a;
        // if (cin.fail())
            // throw runtime_error("not a number!");
    // }catch(runtime_error e){
        // cout << e.what() << endl;
        // goto retry;
    // }
    while(!(cin >> a)){
        cout << "not a number!" << endl;
    }
    do{
        result *= a;
    }while(a-- > 1);
    cout << "result is:\n\t" << result << endl;
    return 0;
}
  • 写回答

2条回答 默认 最新

  • Tiger_Zhao 2016-12-13 06:02
    关注

    首先:出错后,cin.fail() 这种状态一旦标记上后就一直为真,需要用 cin.clear(); 清除状态。
    其次:出错后,原先导致错误的字符还在输入缓冲区,你继续用一样的方法读取还是一样的错误。应该用 cin.ignore(); 丢弃一个字符。
    加上上面这两句代码。

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器