【问题标题】:Else statement crashes when i enter a letter for a cin << int value当我为 cin << int 值输入一个字母时,Else 语句崩溃
【发布时间】:2011-03-01 09:02:05
【问题描述】:

好的,我有一个问题,我不再使用字符串进行选择,所以现在我使用整数。当用户输入一个数字时,游戏就会进行。如果他们输入了错误的字符,它应该给出 else 语句,但是如果我输入一个字母或字符,系统会进入无限循环效果然后崩溃。即使用户定义了变量的类型,有没有办法给出 else 语句。

// action variable;
int c_action: 

if (c_action == 1){
    // enemy attack and user attack with added effect buffer. 
    ///////////////////////////////////////////////////////
    u_attack = userAttack(userAtk, weapons);
    enemyHP = enemyHP - u_attack;

    cout << " charging at the enemy you do " << u_attack << "damage" << endl;
    e_attack = enemyAttack(enemyAtk);
    userHP = userHP - e_attack;
    cout << "however he lashes back causing you to have " << userHP << "health left "  << endl << endl << endl << endl;
    //end of ATTACK ACTION
}else{
    cout << "invalid actions" << endl;
    goto ACTIONS;
}

【问题讨论】:

  • 您还没有显示读取用户输入的行。
  • 我想 'goto ACTIONS' 可以替换为适当的函数调用。
  • 你能对格式做点什么吗?这太可怕了,我只是不想打扰。此外,我看到了 else 但没有 if。
  • goto ACTIONS; // here be raptors
  • 看起来我们三个人同时修复了代码布局,哈哈。这让我的眼睛流血了。

标签: c++ int if-statement


【解决方案1】:

你还没有展示你是如何读取整数的。但总的来说,你想做这样的事情:

int answer;
if (cin >> answer)
{
   // the user input a valid integer, process it
}
else
{
   // the user didn't enter a valid integer
   // now you probably want to consume the rest of the input until newline and
   // re-prompt the user
}

【讨论】:

  • 具体来说,类似 cin.clear(); cin.ignore(numeric_limits::max(), '\n');
【解决方案2】:

问题是您的 cin 正在抓取字符然后失败,从而将字符留在输入缓冲区中。您需要检查 cin 是否有效:

if( cin >> k) { ... }

cin >>k;
if(!cin.fail()) { ... }

如果失败,清除缓冲区和失败位:

cin.clear(); // clears the fail bit
cin.ignore(numeric_limits<streamsize>::max()); // ignore all the characters currently in the stream

编辑:numeric_limits 位于限制头文件中,您照常包含该文件:

#include <limits>

【讨论】:

  • 我一定是得到了错误的代码之类的,因为我在 OP 代码中没有看到 cin 的单一使用。
  • @Noah Roberts:他提到无限循环是由于用户输入字符而不是数字造成的。我还评论了他之前提出的关于 cin 的问题,所以我认为这是后续问题。
【解决方案3】:

您的问题不在于 else 语句,而在于您的输入。如果你做类似的事情

cin >> i;

并输入一个字符,流错误状态被设置,任何后续尝试从流中读取都将失败,除非您先重置错误状态。

您应该改为读取字符串并将字符串内容转换为整数。

【讨论】:

  • 谢谢,这是个好主意,我正在自学 C++,所以我有很多问题。
  • @Timothy:不要成为一个快乐的杀手,但那样你只会伤害自己的知识。拿一本好书。 stackoverflow.com/questions/388242/…
猜你喜欢
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2012-08-07
  • 2023-04-02
  • 1970-01-01
  • 2019-05-31
  • 2018-05-06
相关资源
最近更新 更多