按回车键继续

问题描述 投票:35回答:6

这不起作用:

string temp;
cout << "Press Enter to Continue";
cin >> temp;
c++ string newline cin
6个回答
74
投票
cout << "Press Enter to Continue";
cin.ignore();

或更好:

#include <limits>
cout << "Press Enter to Continue";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');

9
投票

尝试:

char temp;
cin.get(temp);

或者更好的是:

char temp = 'x';
while (temp != '\n')
    cin.get(temp);

我认为字符串输入会等到你进入真实人物,而不仅仅是一个换行符。


8
投票

替换为您cin >> temp

temp = cin.get();

http://www.cplusplus.com/reference/iostream/istream/get/

cin >>将等待EndOfFile。默认情况下,CIN将有skipws标志设置,这意味着它被提取出来并把你的字符串之前,它跳过'任何空白。


2
投票

尝试:

cout << "Press Enter to Continue";
getchar(); 

如果成功,则字符读取被返回(提升到int值,int getchar ( void );),它可以在测试块(while等)一起使用。


2
投票

您需要包括CONIO.H那么试试这个,这很容易。

#include <iostream>
#include <conio.h>

int main() {

  //some code like
  cout << "Press Enter to Continue";
  getch();

  return 0;
}

这样,您不需要为这只是getch();字符串或int


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);
}

我发现这得益于此questionanswer后,我发现,std::cin >> temp;不空的输入返回。所以我想知道如何应对可选用户输入(这是有道理的,一个字符串变量当然可以为空)。

© www.soinside.com 2019 - 2024. All rights reserved.