简体   繁体   English

您如何在C ++中“按ENTER继续,其他所有要退出”

[英]how do you “Press ENTER to continue, anything else to quit” in C++

Sorry, I'm sure this question gets asked a million times. 抱歉,我确定这个问题被问了一百万遍。 I've searched, and I've found answers for "Press ENTER to continue", but for the life of me, I can't find the answer to my question. 我已经搜索过,并且找到了“按ENTER键继续”的答案,但是对于我一生来说,我找不到我的问题的答案。

do{
   //something something
   cout<<"Press ENTER to continue or anything else to quit."<<endl;
   //Enter is pressed or something else
}while(Enter is pressed)

here's what I'm trying to use it for 这是我正在尝试将其用于

do{
   cout<<"Enter value: ";
   cin>>value[n];

   cout<<"Enter 'Y' to continue, anything else to quit"<<endl;
   cin>>reply;
}while(reply == 'y' || reply == 'Y')

In place of "Enter 'Y' to continue. Anything else to quit." 代替“输入'Y'继续。其他所有退出。”。 I just want an "Enter to continue, Q to quit". 我只希望“ Enter继续,Q退出”。

edit : After implementing what Tony D showed, I now have 编辑 :实施托尼·D所示后,我现在有

do{
    cout<<"Enter the person's first name, last name, and age."<<endl;
    cin>>list[n].firstName>>list[n].lastName>>list[n].age;

    n++;
    cout<<"Press ENTER to continue. 'Q' to quit. ";
    std::getline(std::cin, reply);
}while (std::getline(std::cin, reply) && reply != "Q" && reply != "q"); 

it works, but I feel like something is still wrong. 它可以工作,但我感觉还是有问题。 If I do just while (std::getline(std::cin, reply) && reply != "Q" && reply != "q"); 如果我只是这样做while (std::getline(std::cin, reply) && reply != "Q" && reply != "q"); Q or q won't exit the loop and Enter just takes me to the next line. Q或q不会退出循环,而Enter只是将我带到下一行。 I tried this as a do while and a while loop. 我尝试了做这一段时间循环。

Firstly, when you do streaming like this (adding error handling)... 首先,当您像这样进行流式传输(添加错误处理)时...

if (!(cin>>list[n].firstName>>list[n].lastName>>list[n].age))
{
    std::cerr << "oops... unable to parse `firstname lastname age' from stdin... terminating\n";
    return EXIT_FAILURE;
}

...the parsing of input for age terminates on and does not consume the first whitespace character following. ...针对age的输入解析终止,并且不消耗后面的第一个空格字符。 That means the terminating newline will always be left on the cin stream. 这意味着终止的换行符将始终留在cin流中。 So, you need to do something to get rid of it. 因此,您需要采取一些措施来摆脱它。 A simple way to do that while making it clear that you're not interested in the rest of the line's content is: 明确表明您对该行其余内容不感兴趣的一种简单方法是:

std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');

If you prefer to check everything really carefully, you could use std::getline(std::cin, line) to read the line of input into a std::string , then construct a std::stringstream with it, then parse out the content like this: 如果您想真正仔细地检查所有内容,则可以使用std::getline(std::cin, line)将输入的行读入std::string ,然后构造一个std::stringstream ,然后解析出内容如下:

std::string line;
if (cin>>list[n].firstName>>list[n].lastName>>list[n].age))
{ 
     std::istringstream iss(line);
     if (!(iss >> firstName >> lastName >> age))
     {
        std::cerr << "oops... unable to parse `firstname lastname age' from stdin... terminating\n";
        return EXIT_FAILURE;
     }

     char c;
     if (iss >> c)  // this should fail - no more non-whitespace content allowed...
     {
        std::cerr << "oops... extra input encountered after the age value... terminating\n";
        return EXIT_FAILURE;
     }
}

Once we're sure you're reading the entire line of per-person input, for the loop termination itself it's probably easiest to use: 一旦确定您正在阅读每人输入的整行内容,对于循环终止本身,它可能是最容易使用的:

do
{
    ...
} while (std::getline(std::cin, my_string) && my_string != "Q" && my_string != "q");

That way, any newline characters will automatically be removed from the stream. 这样,所有换行符都会自动从流中删除。 Using std::cin.get() to read a single character from the stream is possible and more efficient, but it's a little trickier handling the newline. 使用std::cin.get()从流中读取单个字符是可能的,并且效率更高,但是处理换行符有点棘手。 Can get fancier if you want to ignore leading whitespace, complain about other non-empty input etc.. 如果您想忽略前导空格,抱怨其他非空输入等,可以变得更奇特。

Whatever you type may not reach the stream until you press enter, so they'll need to press 'Q' to quit. 除非您按Enter键,否则您键入的任何内容都不会到达信息流,因此他们需要按“ Q”键退出。 To avoid that, you'd need OS-specific non-Standard code or libraries. 为避免这种情况,您需要特定于操作系统的非标准代码或库。 There are plenty of SO questions explaining how to read keys without waiting for enter. 有很多SO问题说明如何在不等待输入的情况下读取键。


If you need to tolerate errors and prompt the user to try again, the easiest approach is to read in a way that can't fail due to invalid input, then use a separate stream object when you're attempting the parsing that may fail. 如果您需要容忍错误并提示用户重试,最简单的方法是以一种不会因输入无效而失败的方式进行读取,然后在尝试可能失败的解析时使用单独的流对象。 The following shows how to parse a few variables out of a line of input: 下面显示了如何从输入行中解析一些变量:

std::string line;
while ((std::cout << "enter x y z (space separated): ") &&
       std::getline(std::cin, line))
{
    std::istringstream iss(line); // input string stream with contents of last line read
    char c;
    if ((iss >> x >> y >> z) && !(iss >> c))
        // we successfully parsed out x, y and z, and there was no trailing
        // non-whitespace character, so all's good...
        break;
    std::cerr << "unable to parse 'x', 'y' and 'z' from input, or unexpected trailing text\n";
    std::cerr << "please try again\n";
}

This way, iss may enter a bad state due to merely bogus user input but is recreated with the next line's content anyway. 这样, iss可能由于仅是虚假的用户输入而进入不良状态,但无论如何还是用下一行的内容重新创建。 std::cin only fails on unrecoverable issues (end-of-file, hardware error etc). std::cin仅在不可恢复的问题(文件结束,硬件错误等)下失败。 That avoids having to reset any stream state, which is a painful thing to have to do, see http://support.microsoft.com/kb/132422 for an example program showing how. 这样可以避免必须重置任何流状态,这是一件很痛苦的事情,有关示例程序,请参阅http://support.microsoft.com/kb/132422

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

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