Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this program work?

Tags:

c++

stack

I recently wrote a program that takes inputted char data, tests if it is acceptable (a-z, # marks the end of the input) and puts it in a stack which then tests to see if it's a palindrome. I was expecting to enter it one char by a time, but if I enter a string ended by pound it.. works. Here is some of the relevant code:

char buffer;
bool pound_test = false;
bool palindrome = false;
bool keep_going = true;
stack<char> stack1, stack2, stack3;
string str = "";

cout << "Please enter a string, then end it with the pound sign. " << endl;

while(pound_test == false) {
    cin >> buffer;

    if((buffer >= 97) && (buffer <= 122))
    {
        stack1.push(buffer);
        stack2.push(buffer);
        str += buffer;
    }

    if((buffer >= 65) && (buffer <= 90)) {
        buffer = buffer + 32;
        stack1.push(buffer);
        stack2.push(buffer);
        str += buffer;
    }

    if(buffer == '#')
        pound_test = true;
}

So, when the user enters one long string, like "racecar#" and presses enter, the program properly puts it into the stack. My question is simply: why? Wouldn't the data have to be inputted one char at a time for it to work properly, because the cin is in the loop itself, and the loop has to repeat to enter multiple chars into the stack, right? Thanks!

Edit: Thanks for the answers/comments everyone! I'm really impressed by the quick and kind replies. I'm certainty going to use this site again.

like image 939
Nathan Avatar asked Jan 18 '23 16:01

Nathan


1 Answers

Console input (via the cin std::istream object) in most systems is line buffered. So when you call cin::operator>> for a single character, the function does not in fact return until you press newline (because the underlying I/O system does not make data available to cin until then). Any data entered up-to and including the <newline> will be buffered and subsequent calls to cin::operator>> will be serviced from the buffer until it is exhausted.

In this case cin >> buffer, where buffer is of type char will indeed get a single character, but before that the console buffered an entire line and will use it to satisfy subsequent console input operations.

If you step through your code in your debugger the operation may be clearer to you.

like image 175
Clifford Avatar answered Jan 25 '23 12:01

Clifford