getline(cin,mystr) and while loops

I am working on a program that is a simple math game and I have a function called add but for some reason my while loop wont stop for my getline(cin,mystr). I cant figure out whats wrong??????


while(endAdd==false)
{

cout<<"Question#"<<counter++<<"\t";

time_t seconds;
time(&seconds);

srand((unsigned) seconds);
num1= rand()%11;
num2= rand()%11;
cout<<num1<<" + "<<num2<<" = ";
getline(cin,mystr);////////here is my issue...it gets ignored
stringstream(mystr)>>answer;/////////



if(answer==(num1+num2))
cout<<"CORRECT!!!!! the answer is "<<num1+num2<<endl<<endl;
else//////////////////then jumps straight to this else
cout<<"SORRY, WRONG ANSWER!!!!"<<endl<<endl;

cout<<"If you would like to continue type <y> for yes, or <n> for no:";


cin>>keepGoing;




if(keepGoing=='y'){endAdd=false;}

if (keepGoing=='n'){endAdd=true;}

else if (keepGoing!='n'&& keepGoing!='y')
{

while(keepGoing!='n'&& keepGoing!='y')
{
cout<<endl<<endl<<"INCORRECT RESPONSE!!! Please type <y> for yes or <n> for no:"<<endl<<endl;
cin>>keepGoing;

if(keepGoing=='n'){endAdd=true;}
}

}
}////////end while
This may be it:

When you use cin>>, you leave a newline ('\n') in the buffer from when the user pressed Enter. When you get to the getline(), it sees that newline and assumes the user is done inputting, reading in an empty string.

You can try using cin.ingore() to get rid of that extra whitespace, or use getline() everywhere you want input.
Topic archived. No new replies allowed.