输入验证难题

时间:2012-11-10 04:08:53

标签: c++ validation

我刚写了一个非常简单的输入验证算法。我觉得它很不错,但是当我测试时,我看到了一些我不理解的东西。首先是代码。

#include <iostream>
#include <cstdlib>
#include <sstream>
#include <string>

using namespace std;

int main()
{
cout << "Simple Menu"
    << "\n\t\t1. Input"
    << "\n\t\t2. Exit" << endl;

string input = "";

int myNum = 0;

char myChar = {0};

do
{
    cout << "Please enter a valid menu option: ";
    getline(cin,input);

    if (!(stringstream(input) >> myNum))
    {
        cout << "Please enter a valid menu option: ";
        getline(cin,input);
    }           

}while(myNum < 1 || myNum > 5 || input.length() != 1);

cout << "\nThe menu option you entered is: " << myNum << endl << endl;

return 0;       
}

原来,如果我把.1作为选择,它会要求我输入一个有效的选项,这很好。但是,如果我在输入.1之后立即输入2(一个有效选项),它仍会作出反应,好像我输入了一个错误值。以下是此类事件的控制台窗口:

Simple Menu
                1. Input
                2. Exit
Please enter a valid menu option: .1
Please enter a valid menu option: 2
Please enter a valid menu option: 2

The menu option you entered is: 2

Press any key to continue . . .

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:3)

您当前的代码:

do
{
    cout << "Please enter a valid menu option: ";    // first prompt
    getline(cin,input);                              // you enter .1

    if (!(stringstream(input) >> myNum))
    {
        cout << "Please enter a valid menu option: ";// second prompt
        getline(cin,input);                          // this data is discarded
    }           

}while(myNum < 1 || myNum > 5 || input.length() != 1);

更改为:

do
{
    cout << "Please enter a valid menu option: "; // first prompt
    getline(cin,input);                           // .1

    if (!(stringstream(input) >> myNum)) continue;// if parsing fails loop back
} while(myNum < 1 || myNum > 5 || input.length() != 1);

进一步简化为:

myNum = -1;
do
{
    cout << "Please enter a valid menu option: "; // first prompt
    getline(cin,input);                           // .1

    stringstream(input) >> myNum;
} while(myNum < 1 || myNum > 5);

答案 1 :(得分:1)

追踪你的逻辑,它做你告诉它的东西。你想要的是这样的东西

string input;
int myNum = -1;
while(myNum < 1 || myNum > 5 || input.length != 1){
    cout << "Please pick a valid menu options: ";
    getline(cin,input);
    stringstream parser(input);
    if(! (parser >> input )){
       input.clear();
       myNum = -1;
    }  
}