std::cin loops even if I call ignore() and clear()

主宰稳场 提交于 2019-12-01 22:49:14
R Sahu

When the stream is in an state of error,

  cin.ignore();

does not do anything. You need to call cin.clear() first before calling cin.ignore().

Also, cin.ignore() will ignore just one character. To ignore a line of input, use:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Add

#include <limits>

to be able to use std::numeric_limits.

The fixed up block of code will look something like:

int num;
while ( !(cin >> num) ) {
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   cout << "Enter valid number: " << endl;
}

The ignore() has no effect when the stream is in fail state, so do the clear() first.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!