ok so i have a do- while loop and I'm trying to format it so when the user types a y or just leaves it blank and hits the enter button it gives a true statement but so far everytime I test by just hitting enter it just keeps newlining. Some help with what to do will be great. thank you guys!
1 2 3 4 5 6 7 8 9 10 11 12 13
do
{
cout << "hello !!!\n"
<< "would you like another greeting?(y\n)\n";
cin << response;
if((toupper(response) == 'Y')||( response == '\n'))
{
}
else
{
break;
}
}while(true);
I'm not sure if it works or not, and I can't test it right now, but maybe try using the ASCII table to find the decimal or hexadecimal equivalent of "carriage return" ?
Use cin.get() function.
I used it some time ago to capture Enter key press("Press enter key to continue"), so you will have no problem using it for your task.
PS. I would recommend you abandoning infinite loop and break statement in favor of bool that would control your loop. Something like this
1 2 3 4 5 6 7 8
bool exit = false;
do
{
//Do something
//Get input
//If input is what you wanted( not Y or y in your case) exit = true
}while(exit == false )
Duoas is right, preferred way is getline; I just thought of me skipping enter first, and recalled std::get() function, but both methods work. Getline is just more simple and elegant.
@i like red pandas
There was nothing wrong with your answer -- you shouldn't go back and delete stuff.
Dealing with user input is not anywhere near as simple as we tend to think it is (or ought to be).
C++'s stream operators are powerful and tend to lull us into the idea that just getting input and correctly parsing a stream are one and the same. Other languages make it a little less flexible and/or more pedantic.
For example, in Python, to get input you must mystring = raw_input(). Once you have that, you can try to convert it/parse it to whatever you want, which Python makes easy with dynamic typing and built-in string/list processing capabilities.
In C++, you must be a little more explicit about it, and put the sanity checks in all the right spots.
For example, the snippet I posted works because a c-string always has at least one character -- the terminating null. So by checking against the first character in the c-string, there cannot ever be an error on that test -- even if the input stream is in an error state. It is a simple trick for getting a single unconditional character from the user, given the following mantra:
The user will always press ENTER at the end of every input.