c ++验证输入不起作用

时间:2016-10-05 22:05:34

标签: c++

我正在编写下面的代码并且一切正常工作,除非我输入多个字符时它假设在没有退出程序的情况下给出无效输入但是当我写了多个字符开始相当'Q'或'q'时会发生什么退出程序,我不希望我只想输入'q'或'Q'

int main()
{
    char grade;

    while(grade!='Q'&& grade!='q') {

        cout<<"\nEnter one grade Letter from the following"
            <<" (A ,B,C,D or F) or Please or 'q' to quite: ";

        cin>>grade;
        if (cin.get() != '\n') // Look at the next character
            {

                cin.ignore(1000, '\n'); // Clear the input stream

                cout << "\nInvalid input !\n";
            }

        else if (grade != 'A' && grade != 'a'
                 &&  grade != 'B' && grade != 'b'
                 &&  grade != 'C' && grade != 'c'
                 &&  grade != 'D' && grade != 'd'
                 &&  grade != 'F' && grade != 'f'
                 &&  grade != 'Q' && grade != 'q'
                 ) {

            cout << "\nInvalid input !\n";

        }

        else if(grade =='A'||grade=='a')
            cout<<"Excellent"<<endl;
        else if(grade=='B'|| grade=='b')
            cout<<"Good"<<endl;
        else if(grade=='C' || grade=='c')
            cout<<"Fair"<<endl;
        else if (grade=='D' || grade=='d')
            cout<<"Poor"<<endl;
        else if (grade=='F' || grade=='f')
            cout<<"Failure"<<endl;
        //else

    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

如果您不想仅考虑输入的第一个字符,则不要读取单个字符,然后根据它做出所有决定。使用std::getline()将整行读入std::string,然后检查有效值。

此外,您现有的代码具有未定义的行为,因为grade在首次使用之前未初始化。