* Pretext - i.e., it's homework, but I'm not looking for "the" answer *
I'm currently in my first C++ programming class and was looking for some help. I like to try to challenge myself on homework assignments by including things that aren't necessary but, realistically, are something you would want in a real world scenario. More specifically, with our homework assignments, all that is required is a single run of a program. However, for most programs, I like to insert a loop that allows you to continue the program without having to relaunch it. This week, we started learning about strings which is causing a conflict with the loop I had always used.
**** Problem ****
Basically, I would always loop my programs with a char variable as I can use toupper() to modify the input. However, now the first thing being executed in a loop is a getline(). On the first run, everything is fine. When I get to the "Would you like to play again" portion and I assign a "Y" to the playAgain, the loop repeats and the cout prior to the getline() displays twice. Technically the program still functions, but it obviously is not very aesthetically pleasing...
My understanding is that it is probably caused by the '/n' that is technically at the end of the char variable creating an invalid value for my getline(), executing it twice. The problem is, if I use cin.ignore before it, my program just displays completely blank.
Is there another way to get around this? Or do I need to start using a different solution for the loop?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
int main()
{
string origWord = "";
char playAgain = 'Y';
string displayWord = "";
while (toupper(playAgain) != 'N')
{
if (toupper(playAgain) == 'Y' || toupper(playAgain) == 'N')
{
while (toupper(playAgain) == 'Y')
{
system("cls"); // Clears previous game in loop
while (origWord.length() < 1)
{
cout << "Enter a word in uppercase: ";
getline(cin, origWord);
[*The rest of the actual "program" goes here*]
} // End while
origWord = ""; // Resets word length
cout << endl << endl << "Would you like to play again? (Y/N): ";
cin >> playAgain;
} // End "Y" While
} // End of "if" portion of if
else
{
cout << endl << "Invalid selection, please try again." << endl;
cout << "Would you like to play again? (Y/N): ";
cin >> playAgain;
} // End else
}// End while
return 0;
} // End of main function
|