While loop with try catch fails at bad cin input

后端 未结 6 1943
耶瑟儿~
耶瑟儿~ 2020-12-11 09:05

I can\'t seem to figure out why this falls into a loop after getting non-int input. I\'ve tried cin.flush(), which doesn\'t seem to exist, cin.clear(), which seems like it s

6条回答
  •  轮回少年
    2020-12-11 09:36

    It looks like you would be better off with iostream's native exceptions. Enable with

    cin.exceptions( ios::failbit );
    
    try {
       …
    } catch( ios_base::failure & ) {
      cin.clear();
      …
    }
    

    Never, ever throw an an object not derived from std::exception, and especially not a native type like char*.

提交回复
热议问题