lundi 30 mars 2015

while loop and getchar()

I have the simple program below that I wrote for a college course. I know it doesn't really do anything, but it's just an assignment for a course.


The part that I can't figure out, is why doesn't the outer loop work?


The user needs to press '1' to continue, and any other key the program exits.


However, it still doesn't continue if the user presses '1' and instead exits anyway.


I tried adding a cin.clear() before cin >> repeat, but that doesn't work.


I also tried playing around with cin.ignore(), but that didn't seem to help either.


Any ideas?


Thanks



int main()
{
int repeat = '1';
stack<char> cstr;
char c;

while (repeat == '1')
{
cout << "Enter in a name: ";

while (cin.get(c) && c != '\n')
{
cstr.push(c);
}

cout << "\n Enter another name? 1 = Continue, any other key to exit the program";
cin >> repeat;
repeat = getchar();
}
}

Aucun commentaire:

Enregistrer un commentaire