I have written similar code before and I can not figure out what is wrong this time. All variables are declared as int and assigned to 0 prior to this section.( with exception to "people as 1")
The issue: When the user inputs a letter I get an infinite loop running the default case. I tried clearing the cin buffer and assigning the selecter variable back to 0 and neither option fixed my loop. Any insight would be appreciated.
for(; selecter!=-1; people++)
{
cout<<"Please input person number "<<people<<"'s favorite drink.\n";
cout<<"1 for Coffee.\n";
cout<<"2 for Tea.\n";
cout<<"3 for Coke.\n";
cout<<"4 for Orange Juice.\n";
cout<<"-1 to end survey with totals.\n";
cout<<"Selection: ";
cin>>selecter;
switch (selecter)
{
case 1:
coffee++ ;
break;
case 2:
tea++ ;
break;
case 3:
coke++ ;
break;
case 4:
oj++ ;
break;
case -1:
people--;//Dummy to end loop. returns "people" back to original number.
break;
default:
cout<<"That is an invalid entry, please try again."<<endl;
people--;
break;
}
cout<<endl;
}
#include <iostream>
usingnamespace std;
int main()
{
int coffee=0;
int tea=0;
int coke=0;
int oj=0;
int selecter=0;
int people=1;
bool quit=false;
while(quit==false)
{
cout<<"Please input person number "<<people<<"'s favorite drink.\n";
cout<<"1 for Coffee.\n";
cout<<"2 for Tea.\n";
cout<<"3 for Coke.\n";
cout<<"4 for Orange Juice.\n";
cout<<"-1 to end survey with totals.\n";
cout<<"Selection: ";
cin>>selecter;
switch (selecter)
{
case 1:
coffee++ ;
break;
case 2:
tea++ ;
break;
case 3:
coke++ ;
break;
case 4:
oj++ ;
break;
case -1:
people--;
quit=true;
break;
default:
cout<<"That is an invalid entry, please try again."<<endl;
// selecter=0;
people--;
break;
}
people++;
cout<<endl;
}
people--;
cout<<people<<" have been surveyed.\n";
cout<<"The results:\n";
cout<<"Coffee: "<<coffee<<endl;
cout<<"Tea: "<<tea<<endl;
cout<<"Coke: "<<coke<<endl;
cout<<"Orange Juice: "<<oj<<endl;
}
(have tried with and without the selecter variable commented out in the default case.)
> When the user inputs a letter I get an infinite loop running the default case.
When the attempted input fails, the stream is put into a failed state;
the stream must be put back into a good state before any further i/o can be performed.
In addition, the character(s) that caused input failure remain in the input buffer; these must be removed.
I had tried adding the cin.clear() line before and thought that was all I needed forgot about cin.ignore( 1000, '\n' ) Still taking my first few steps into c++ and my understanding of the buffer is still a bit lacking. Guess I have a topic to bring to class next week. The code runs correctly now. Thank you very much.