简体   繁体   中英

Stopping while-loop with std::cin input

I'm currently trying to create a loop that should only stop if the user enters "quit", "Quit" or something similar. I tried a few variations already but I need it to execute the rest of the loop and not stop to wait for an Input.

Running = true;
while(Running)
  {
    char c;
    std::cout << "test ";
    c = std::cin.peek(); 
    if(c=='Q'|| c=='q')
    {
    Running = false;
    }
  }

Any help would be greatly appreciated.

Aside from peek() returning int_type , not char ...

...it reads the next character from the stream without actually extracting it .

Since your cin does, at this point, not contain anything (unless you piped something to your program, or already typed something), the call will block until there is a character to be peek() ed.

Since, using <iostream> , your program does not actually receive input until you press Enter , that is what your program does: Waiting until you entered something, and pressed Enter .

Only then does the program check whether the first character you entered is "q" or "Q". The line you entered, including that first character, will remain in the stream -- so the next time you peek() , it will still be the very same character.

Solution? There is no non-blocking query of cin in the C++ standard library. You either have to work with threads, or refer to some third-party input handling (like the getch() function offered by eg Microsoft Windows or the NCurses library).

Do it simply this way.

std::string input;
cin>>input;
while(input!="quit" && input!="Quit")
{
// do something;
// get input.
}

Not sure what you mean by

I need it to execute the rest of the loop and not stop to wait for an Input.

But if you replace c=std::cin.peek() by std::cin >> c , infinite loop problem will be solved.

Running = true;
while (Running)
{
    char c; 
    std::cin >> c;
    std::cout << "test";

    if (c == 'Q' || c == 'q')
    {
        Running = false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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