0

我刚刚写了一个非常简单的输入验证算法。我认为它很好,但是当我测试它时,我看到了一些我不明白的东西。这里首先是代码。

#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 . . .

知道这是为什么吗?

4

2 回答 2

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);
于 2012-11-10T04:19:55.557 回答
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;
    }  
}
于 2012-11-10T04:26:09.187 回答