Here's a fairly simple piece of code to get a message from the user, limiting its length to 10 chars. Problems arise when the message is 10 chars or more, and the program enters an infinite loop.
I think the problem is getline() leaving somethin on the stream, but I've tried using cin.ignore() to clear it, but it just doesn't happen.
Any help would be greatly appreciated.
#include <iostream>
using namespace std;
void main(){
bool exitProgram = false;
char selection, message[20];
while(!exitProgram){
cout << "Press 1 to continue or 2 to quit: ";
cin.get(selection);
cin.sync();
cout << endl;
while(selection != '1' && selection != '2'){
cout << "choose 1 or 2: ";
cin.get(selection);
cin.sync();
cout << endl;
}
if(selection == '1'){
cout << "type a message. Messages will be shortened to 9 chars\n> ";
cin.getline(message, 10);
cout << "Your message: " << message << endl;
}
else{
cout << "terminating\n" << endl;
exitProgram = true;
}
}
}