【问题标题】:C++ | Take User Input without giving a valueC++ |接受用户输入而不给出值
【发布时间】:2017-05-06 04:10:50
【问题描述】:

我可以看到标题可能有点混乱。基本上我希望用户按 Enter 10 次以结束循环。但我实际上必须输入一些东西才能计数,我认为这是因为我给了“无用”一个 char 数据类型,但我会分配什么,这样我就可以按 Enter 键了?谢谢!

void mineFunc(){
//Mining Function
int durability = 10;
char useless; //Just so user can tap enter to 'mine'
cout << "Tap Enter to Mine" << endl;
do {
    cin >> useless;
    durability -= 1;
    cout << "Durability: " << durability << endl;
} while (durability > 0);
gold += 5;

}

【问题讨论】:

  • cin.get(useless);
  • 使用std::getline()std::istreams getline()成员函数从std::cin而不是cin &gt;&gt; useless读取一行输入。
  • 我同意 M.M.... 打败我。只需替换 cin >> 没用;用 cin.get(没用);有趣的小游戏哈哈。

标签: c++ input


【解决方案1】:

好吧,您可以在流上使用 IO 操纵器 std::noskipws,但由于它是 cin,您可能不想让它处于该状态。而且您必须保存/恢复以前的状态才能与程序的其他部分配合使用。

更简单的方法是循环如下:

while( cin && cin.get() != '\n' );

现在,如果流失败,您想跳出循环。你可能想把它包装得更好一点:

istream & wait_enter( istream & s )
{
    while( s && s.get() != '\n' );
    return s;
}

那么你有:

do {
    if( !wait_enter(cin) ) break;
    durability -= 1;
    cout << "Durability: " << durability << endl;
} while (durability > 0);

由于 IO 操纵器的工作原理,您甚至可以这样做(如果您喜欢这种风格):

    if( !(cin >> wait_enter) ) break;

【讨论】:

    【解决方案2】:

    您可以使用std::getline。如果您在空行时按 Entergetline 将返回一个空行。

    std::string dummyLine;
    while ( durability > 0 && getline(std::cin, dummyLine) )
    {
       --durability;
    }
    

    while 语句中使用上述条件可确保如果您输入EOF,则循环退出并且不会永远卡在那里。

    【讨论】:

      【解决方案3】:

      感谢大家的帮助!

      我找到了

      cin.get(useless);
      

      成为解决此问题的最简单最有用的方法。

      【讨论】:

        猜你喜欢
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-26
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多