这不起作用:
string temp;
cout << "Press Enter to Continue";
cin >> temp;
cout << "Press Enter to Continue";
cin.ignore();
或更好:
#include <limits>
cout << "Press Enter to Continue";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
尝试:
char temp;
cin.get(temp);
或者更好的是:
char temp = 'x';
while (temp != '\n')
cin.get(temp);
我认为字符串输入会等到你进入真实人物,而不仅仅是一个换行符。
替换为您cin >> temp
:
temp = cin.get();
http://www.cplusplus.com/reference/iostream/istream/get/
cin >>
将等待EndOfFile。默认情况下,CIN将有skipws标志设置,这意味着它被提取出来并把你的字符串之前,它跳过'任何空白。
尝试:
cout << "Press Enter to Continue";
getchar();
如果成功,则字符读取被返回(提升到int
值,int getchar ( void );
),它可以在测试块(while
等)一起使用。
您需要包括CONIO.H那么试试这个,这很容易。
#include <iostream>
#include <conio.h>
int main() {
//some code like
cout << "Press Enter to Continue";
getch();
return 0;
}
这样,您不需要为这只是getch();
字符串或int
功能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);
}
我发现这得益于此question和answer后,我发现,std::cin >> temp;
不空的输入返回。所以我想知道如何应对可选用户输入(这是有道理的,一个字符串变量当然可以为空)。