这不起作用:
string temp;
cout << "Press Enter to Continue";
cin >> temp;
答案 0 :(得分:73)
cout << "Press Enter to Continue";
cin.ignore();
或者,更好:
#include <limits>
cout << "Press Enter to Continue";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
答案 1 :(得分:9)
尝试:
char temp;
cin.get(temp);
或者,更好的是:
char temp = 'x';
while (temp != '\n')
cin.get(temp);
我认为字符串输入会等到您输入真实字符,而不仅仅是换行符。
答案 2 :(得分:8)
将您的cin >> temp
替换为:
temp = cin.get();
http://www.cplusplus.com/reference/iostream/istream/get/
cin >>
将等待EndOfFile。默认情况下,cin将设置 skipws 标志,这意味着它会在提取并放入字符串之前“跳过”任何空格。
答案 3 :(得分:2)
尝试:
cout << "Press Enter to Continue";
getchar();
成功时,返回字符读取(提升为int
值int getchar ( void );
),可以在测试块(while
等)中使用。
答案 4 :(得分:2)
你需要包含conio.h所以试试这个,这很容易。
#include <iostream>
#include <conio.h>
int main() {
//some code like
cout << "Press Enter to Continue";
getch();
return 0;
}
使用它只需要getch();
答案 5 :(得分:1)
函数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);
}
在我发现std::cin >> temp;
没有返回空输入后,我发现这个感谢question和answer。所以我想知道如何处理可选的用户输入(这对字符串变量有意义当然是空的)。
答案 6 :(得分:0)
还有另一种解决方案,但是对于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;
}