C++ 按 Enter 继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/903221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Press Enter to Continue
提问by Elliot
This doesn't work:
这不起作用:
string temp;
cout << "Press Enter to Continue";
cin >> temp;
回答by rlbond
cout << "Press Enter to Continue";
cin.ignore();
or, better:
或更好:
#include <limits>
cout << "Press Enter to Continue";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
回答by paxdiablo
Try:
尝试:
char temp;
cin.get(temp);
or, better yet:
或者,更好的是:
char temp = 'x';
while (temp != '\n')
cin.get(temp);
I think the string input will wait until you enter real characters, not just a newline.
我认为字符串输入将等到您输入真正的字符,而不仅仅是换行符。
回答by Nick Presta
Replace your cin >> temp
with:
替换cin >> temp
为:
temp = cin.get();
http://www.cplusplus.com/reference/iostream/istream/get/
http://www.cplusplus.com/reference/iostream/istream/get/
cin >>
will wait for the EndOfFile. By default, cin will have the skipwsflag set, which means it 'skips over' any whitespace before it is extracted and put into your string.
cin >>
将等待 EndOfFile。默认情况下,cin 将设置skipws标志,这意味着它会在提取并放入字符串之前“跳过”任何空格。
回答by Ziezi
Try:
尝试:
cout << "Press Enter to Continue";
getchar();
On success, the character read is returned (promoted to an int
value, int getchar ( void );
), which can be used in a test block (while
, etc).
成功时,返回读取的字符(提升为int
值,int getchar ( void );
),该值可用于测试块(while
等)。
回答by HappyMajor
You need to include conio.h so try this, it's easy.
你需要包含 conio.h 所以试试这个,这很容易。
#include <iostream>
#include <conio.h>
int main() {
//some code like
cout << "Press Enter to Continue";
getch();
return 0;
}
With that you don't need a string or an int for this just getch();
有了这个,你不需要一个字符串或一个int getch();
回答by Wolf
The function std::getline(already introduced with C++98) provides a portable way to implement this:
函数std::getline(已在 C++98 中引入)提供了一种可移植的方式来实现:
#include <iostream>
#include <string>
void press_any_key()
{
std::cout << "Press Enter to Continue";
std::string temp;
std::getline(std::cin, temp);
}
I found this thanks to this questionand answerafter I observed that std::cin >> temp;
does not return with empty input. So I was wondering how to deal with optional user input (which makes sense for a string variable can of course be empty).
在我观察到没有以空输入返回后,我发现了这个问题和答案std::cin >> temp;
。所以我想知道如何处理可选的用户输入(这对于字符串变量当然可以为空是有意义的)。
回答by Ricky Gonce
Yet another solution, but for C. Requires Linux.
另一个解决方案,但适用于 C。需要 Linux。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("Press any key to continue...");
system("/bin/stty raw"); //No Enter
getchar();
system("/bin/stty cooked"); //Yes Enter
return 0;
}