I have some problems with cin. When I enter a character instead of an integer cin doesn’t work and after that I can’t even enter a new value. What should I do? I have already tried fflush(stdin)
struct PersonList
{
Person person;
PersonList* personListPtr;
};
void addPerson(PersonList*& ptr, int position);
void deletePersonList(PersonList* ptr);
int main()
{
PersonList* personListPtr = NULL;
int flag = 0;
int pos = 0;
int i;
while(flag != 27)
{
system("cls");
cout << "1 - add objects\n"
<< "2 - delete objects\n"
<< "ESC - exit\n";
switch(flag)
{
case '1':
cout << "Enter position: ";
**cin >> pos;**
addPerson(personListPtr, pos);
break;
case '2':
break;
case '3':
break;
}
flag = _getch();
}
deletePersonList(personListPtr);
return 0;
}
Thanks.
You seem to be mixing several idioms. I don’t know what
_getch()does, but I can’t imagine that it is in anywaycompatible with
std::cin;std::cinwill have (or may have)read ahead, reading your flag character, for example. You
cannot simply mix different streams from the same source.
As for the particular problem you describe, once you enter
something which can’t be converted into what you are reading,
the stream goes into an error state (which you should check
before using the value), and all operations on it become no-ops
until you clear the error (
std::istream::clear()). But that’snot going to fix the other problems. If you insist on using
something like
_getch(), then you’ll have to use it for all ofyour input, building up a string for input of the position, and
using
std::istringstreamto convert it. Depending on what thefunction actually does, you may also have to deal with things
like backspace, enter and maybe even echoing.