【问题标题】:How do I make sure only int, not char, is input? [duplicate]如何确保只输入 int 而不是 char? [复制]
【发布时间】:2019-07-23 09:16:16
【问题描述】:

我编写了一个函数,该函数只有在输入int 时才会执行。如果cin 失败,它将再次执行do{...} while(),直到输入int,而不是char。 我的问题是,一旦我输入char,它就会陷入无限循环。我说不出为什么。

int syst ()
{
    int basisSys;
    bool opAga = false;
    do
    {
        cout << "Type the base you wanna calc. in" << endl;
        cin >> basisSys;
        if (cin.fail())
        {
            opAga = true;
        }
    }
    while (opAga == true);
    cout << endl << "You are calc. in " << basisSys << "system" << endl << endl;
    return basisSys;
}

【问题讨论】:

  • cin 无法读取int 时,字符仍在流中。你正在寻找cin.ignore
  • 不是从流中读取int,而是使用(例如)std::getline() 读取std::string。然后检查字符串的内容以查看它是否包含将被读取为int 的数据。如果是,则从字符串中读取整数值。如果不是,则丢弃输入,然后继续。
  • 通过使用输入运算符&gt;&gt;,您将确保输入是一个数字。尝试将其用作条件,例如:while (cin &gt;&gt; num){//do your stuff}

标签: c++ function loops char int


【解决方案1】:

忽略并清除该行很重要,因为operator&gt;&gt; 不会再从流中提取任何数据,因为它的格式错误。

while(!(cin >> basisSys)){
   cout << "Bad value!";
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

【讨论】:

  • 确实有效。但是为什么我必须清除并忽略? :)
  • 如果发生错误,则设置错误标志,以后尝试获取输入将失败。这就是您需要 cin.clear() 的原因 另外,失败的输入将位于我假设的某种缓冲区中。当您再次尝试获取输入时,它会在缓冲区中读取相同的输入,并且会再次失败。这就是为什么你需要 cin.ignore
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 2019-04-03
  • 2020-06-18
  • 1970-01-01
  • 2014-03-12
  • 2020-01-03
相关资源
最近更新 更多