Reputation: 103
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.
Upvotes: 0
Views: 3629
Reputation: 70391
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 e.g. Microsoft Windows or the NCurses library).
Upvotes: 1
Reputation: 2033
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;
}
}
Upvotes: 0
Reputation: 30936
Do it simply this way.
std::string input;
cin>>input;
while(input!="quit" && input!="Quit")
{
// do something;
// get input.
}
Upvotes: 0