I am having trouble using the cin method to acquire a variable. When the input is a number there is no problem, but when it is a special character like a dot [.],
the whileloop loops into infinity.
What am I doing wrong?
cout << "What is your race" <<endl<<"1.Human\n2.troll\n3.zombie"<<endl;
cin >> *race;
while(*race<1||*race>3)
{
system("cls");
cout << "Wrong choice"<<endl<< "What is your race" <<endl<<"1.Human\n2.troll\n3.zombie"<<endl;
cin >> *race;
}
I searched for the answer and i should have to flush the buffer but i don”t get how to do it. I’m rather new with c++. Thanx
Make
racean char, then you will be able do to:which is probably what you want to achieve.
Explanation:
When you
cin >>into an int, it converts given ASCII string to integer value..doesn’t have an integer meaning, so it isn’t read intoraceandfailbitis set – further >>s are no-op, until you clear them. However, if youcin >>intocharand compare it with otherchars (well, their ASCII codes, actually), you will be able to check it without troubles.