【问题标题】:C++ code buggy, needs fixing [closed]C ++代码错误,需要修复[关闭]
【发布时间】:2013-09-26 03:27:17
【问题描述】:

大家好,我有这段代码,贴在下面。我添加了while循环以确保只使用数字输入,但是当我使用它时,它需要我输入两次数字,或者按回车然后输入数字。

输出将是:

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;
    //}

}

【问题讨论】:

  • 您至少连续两次致电cin &gt;&gt; x - 为什么您对必须输入两次数字感到惊讶?
  • 为什么不把string searchWord = myWords[x]-&gt;word; 移到while 循环之后并删除cin &gt;&gt; x; 行?
  • C++ 非描述性标题,需要修复。
  • 欢迎来到 StackOverflow。为了获得良好的回应,我建议询问有关技术或技术的特定问题。寻求帮助以了解技术(如流)比寻求一般帮助来调试代码块更好。请查看关于页面:stackoverflow.com/about.
  • 我泰山,你简。我的代码错误。你修好了。

标签: c++ validation input


【解决方案1】:

去掉第一个cin &gt;&gt; x;,在while后面设置string searchWord

【讨论】:

  • +1 甚至可能检查x 是否在[0...myWords.size()) 的边界内
  • 我认为在while 循环中还需要一个cin.clear(); 来消除错误标志。
  • 将其更改为while(cin&gt;&gt;x) 并在获得数值时中断循环,这意味着在写入错误之前测试该值。 cin 应该是阻塞的,是不是只有在按键时才会出错?
  • 无论如何我设法修复它,它现在工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
相关资源
最近更新 更多