Frank Scrooby
Frank Scrooby

Reputation: 11

Unexpected behavior from c++ std::cin.get()

Using a book as a tutorial on C++ streams, I typed out the following code:

//include std IO header
#include <iostream>

//start here
int main()
{
    int TypedLetter;

    std::cout << "Press q or Q to end." << std::endl;

    //wait until user types Q or q
    TypedLetter = std::cin.get ();
    while ((TypedLetter != 'q') || (TypedLetter != 'Q'))
    {        
        TypedLetter = std::cin.get ();
    }

    return 0;
}

Simple enough. Straightforward.... Seems impossible for something to go wrong. Right?

Unfortunately, the while TypedLetter != 'q' or 'Q' fails to trap those letters. I can type endlessly until the cows come home and nothing will break this loop.

I am using a relatively modern IDE and compiler (Code::Blocks 20. something). The book is kind of old, but nothing this simple should have changed. All the other samples I've used from the book have worked fine, even the next couple of examples, exploring other aspects of std::cin.xxxxx.

What am I doing wrong? Or, what is my compiler getting wrong? It seems crazy that this code would not work as advertised.

Upvotes: 1

Views: 40

Answers (0)

Related Questions