【问题标题】:getline() gets bypassed without proper user input the first time [duplicate]getline() 第一次在没有正确用户输入的情况下被绕过[重复]
【发布时间】:2013-11-01 11:41:41
【问题描述】:
cout << "Type in your third message below:\n";
getline(cin, msgth);
if (msgth.length() > 0 && msgth.length() < 500) {}
else 
{
    system("cls");
    cout << "Your message has to be between 1 and 500 characters long...";
    goto prot;
}

所以,每当我看到这段代码时,就像它会自动按下回车键,并“跳过”getline() 函数(又名,转到prot 标签)。由于某种原因,同样的事情发生在更远的地方。然而,经过一番试验,我发现在使用这个时:

input:
if (special == 0)
{
    cout << "Choose your input message below:\n";
    getline(cin, inp);
    if (inp.length() > 0 && inp.length() < 500) {}
    else 
    {
        system("cls");
        cout << "Your message needs to be between 1 and 500 characters long\n";
        goto input;
    }
}

第二次确实有效(换句话说,在转到input 标签之后)。这两个代码之间的区别在于,第一个必须绕过std::cin 代码才能返回getline(),而另一个则不需要。
一个解决方案和一些解释将不胜感激。

【问题讨论】:

  • goto 使代码难以理解/遵循。基本不用。
  • 永远不要使用 goto。就是这样。但这不会导致您的问题。
  • 其实我很喜欢用它。但是,我将继续添加一个基于非 goto 的示例。
  • @Max 你可能喜欢用它,你可能明白你在用什么,但其他人不会。
  • @Max 别担心,让问题保持原样。不过,请记住,goto 很少是适合这项工作的工具,而且大多数人都不喜欢它。无论如何,你的问题的答案是here

标签: c++ string getline cin


【解决方案1】:

以下对我有用:

#include <iostream>
#include <string>

int main() {
  std::string str;
start:
  std::cout << "prompt:\n";
  std::getline(std::cin, str);
  if (0 < str.length() && str.length() < 20) {}
  else {
    std::cout << "invalid.\n";
    goto start;
  }
  std::cout << "input: \"" << str << "\"\n";
}

你的和这个有什么不同?

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多