简体   繁体   English

Cin.Ignore()无法正常工作

[英]Cin.Ignore() is not working

Here I have a code: 这里有一个代码:

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

this program will execute and will wait till you press enter and then it will exit. 该程序将执行并等待您按Enter键,然后退出。 now see this code: 现在看到以下代码:

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

this time after entering a number for saving in "m" the program will exit without waiting for cin.ignore command which waits for pressing enter. 这次输入要保存的数字“ m”后,程序将退出,而无需等待等待按enter键的cin.ignore命令。

I mean if you use cin command before cin.ignore, the cin.ignore command will skip. 我的意思是,如果您在cin.ignore之前使用cin命令,则cin.ignore命令将跳过。 why? 为什么? and what should I do for fixing it? 我应该如何解决?

cin.ignore() basically clears any input left in memory. cin.ignore()基本上清除了内存中剩余的所有输入。 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. 在第二段代码中,您使用了>>运算符,该运算符获取格式化的输入,但将结束行字符'\\n' (按ENTER键存储的字符)留在输入缓冲区中。 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). 当您调用cin.ignore()时,它将完成工作并清除该缓冲区。由于已经执行了他所调用的操作,因此只是让程序继续运行(在本例中一直结束)。 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() . 如果您希望用户在程序继续使用cin.get()之前输入一些内容,请记住cin.ignore()用于清除输入缓冲区(保存输入的小内存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<<您之后应调用cin.ignore(),因为它不占用结尾行字符'\\ n',该行字符在您下次要求输入时会被占用,从而导致不需要的结果,例如程序未等待您输入任何东西。

-> cin.get() you should not call cin.ignore() because it consumes the '\\n' -> cin.get()您不应调用cin.ignore(),因为它消耗了'\\ n'

-> getline(cin,yourstring) (gets a whole input line including the end line character) you should also not use cin.ignore() -> getline(cin,yourstring) (获取包括结束行字符的整个输入行),您也不应使用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(); 当您使用cin >> m ,键入cin >> m值,然后按Enter,输入'\\n'进入buffer和cin.ignore(); ignores it and program ends. 忽略它,程序结束。

用这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM