简体   繁体   中英

cin in my program doesn't work properly. How can I fix it?

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 anyway compatible with std::cin ; std::cin will 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's not going to fix the other problems. If you insist on using something like _getch() , then you'll have to use it for all of your input, building up a string for input of the position, and using std::istringstream to convert it. Depending on what the function actually does, you may also have to deal with things like backspace, enter and maybe even echoing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM