I like to put a validation loop around my class assignments that asks the user if they would like to run the program, then ask again if they'd like to re-run the program. However, while working on an assignment, I noticed that my loop works for everything I've written before - but not strings. WHY!?!? Here are two examples of what I'm talking about... first is my loop that works:
Now, here is what I was TRYING to do - getline a string:Code:#include <iostream> #include <string> using namespace std; int main () { char rerun; cout << "Would you like to run this program? (y/n): "; cin >> rerun; while (rerun == 'y' ||rerun == 'Y') { char test[81]; cout << "Type something: "; cin >> test; cout << "You typed : " << test << endl; cout << "Would you like to run this program again? (y/n): "; cin >> rerun; } return 0; }
Code:#include <iostream> #include <string> using namespace std; int main () { char rerun; cout << "Would you like to run this program? (y/n): "; cin >> rerun; while (rerun == 'y' ||rerun == 'Y') { string test; cout << "Type something: "; getline(cin, test); cout << "You typed : " << test << endl; cout << "Would you like to run this program again? (y/n): "; cin >> rerun; } return 0; }
When I run my program and answer the first question with 'y', it does this:
Would you like to run this program (y/n)?: y
Type something: You typed:
Would you like to run this program again (y/n)?:
Press any key to continue...
Why doesn't this second program run?




Reply With Quote