简体   繁体   English

cin在我的程序中无法正常工作。 我该如何解决?

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

I have some problems with cin. 我的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. 当我输入字符而不是整数cin不起作用时,此后我什至不能输入新值。 What should I do? 我该怎么办? I have already tried fflush(stdin) 我已经尝试过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 ; 我不知道_getch()作用,但是我无法想象它与std::cin兼容; std::cin will have (or may have) read ahead, reading your flag character, for example. std::cinstd::cin (或可能已经)阅读,例如阅读您的标志字符。 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() ). 至于您描述的特定问题,一旦输入了无法转换为您正在读取的内容,流就会进入错误状态(在使用该值之前应检查该错误状态),并且对它的所有操作都将变为-直到您清除错误( 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. 如果您坚持使用_getch()类的东西,则必须将其用于所有输入,为位置的输入建立一个字符串,并使用std::istringstream进行转换。 Depending on what the function actually does, you may also have to deal with things like backspace, enter and maybe even echoing. 根据函数的实际作用,您可能还必须处理诸如退格,输入甚至回声之类的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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