Cin.Ignore() is not working

末鹿安然 提交于 2019-11-29 17:14:00

Use this.

std::cin.sync(); std::cin.get();

cin.ignore() basically clears any input left in memory. In the first piece of code, you did not input anything, hence it will have nothing to clear and because of that it waits for you to input something. In the second piece of code you used the >> operator which gets formated input but leaves the end line character '\n' (the one that gets stored when you press ENTER) wandering in the input buffer. When you call cin.ignore() it then does it job and clears that same buffer.As it already did what he was called to it simply lets the program continue (in this case to the end). Remember cin.ignore() is for clearing the input buffer(small piece of memory that holds the input) if you want the user to input something before the program moves on use cin.get().

You should also know this:

If using:

->cin<< you should call cin.ignore() afterwards because it does not consume the end line character '\n' which will be consumed next time you ask for input causing unwanted results such as the program not waiting for you to input anything.

->cin.get() you should not call cin.ignore() because it consumes the '\n'

->getline(cin,yourstring) (gets a whole input line including the end line character) you should also not use cin.ignore()

Use

int m;
cin >> m;
cin.ignore();

cout << "Press Enter To Exit...";
cin.ignore();

when you use cin >> m you type value of m and then press enter, the enter '\n' goes into buffer and cin.ignore(); ignores it and program ends.

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