C ++代码buggy,需要修复

时间:2013-09-20 16:48:14

标签: c++ validation input

嘿伙计们,我已经有了这段代码,发布在下面。我添加了while循环以确保仅使用数字输入,但是当我使用它时,它需要我输入两次数字,或者按Enter然后输入数字。

输出将是:

Input number : 1
1
那么它会打印结果。我怎么能解决这个干杯。

 void Dictionary::SearchNumeric()
{
    int x;
    cout << "Input number : ";
    while (!(cin >> x))
    {
        cout << "Invalid input.  Try again: ";
        cin.ignore(numeric_limits<streamsize>::max());

    }
    string searchWord = myWords[x]->word;
    cout << "Word searched: " << searchWord << endl;
    cout << "Definition: \n" << myWords[x]->definition << endl;
    cout << "Type: " << myWords[x]->type << endl;
    int wordIndex = 0;
    //while (myWords[wordIndex]->word.compare(x) != 0) {
    //needs to return scrabble score
    wordIndex++;
    //break;
    //}

}

1 个答案:

答案 0 :(得分:5)

摆脱第一个cin >> x;,在while

之后设置string searchWord