I recently wrote a program that enters char data, checks if this is valid (az, # indicates the end of the input), and pushes it on the stack, which then checks to see if it is a palindrome. I expected to enter it in one char, but if I enter a line ending with a pound, it works. Here are 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 line, for example "racecar #" and presses enter, the program correctly puts it on the stack. My question is simple: why? Shouldn't the data have to enter one char at a time in order for it to work correctly, because cin is in the loop itself, and the loop has to be repeated to push several characters onto the stack, right? Thanks!
Edit: Thanks for the answers / comments to everyone! I am very impressed with the quick and kind answers. I am sure I will use this site again.
source share