如何在不需要ENTER的情况下接收键输入?

时间:2014-04-20 18:40:44

标签: c++

i=0;
while(i<=20)
{
    nullchoice:
    system("CLS");
    //Advanced Information
    cout << "Your Statistics: " << endl;
    cout << endl << endl;
    cout << "   1  Strength: " << str << endl;
    cout << endl;
    cout << "   2  Vitality: " << vit << endl;
    cout << endl;
    cout << "   3  Agility: " << agi << endl;
    cout << endl;
    cout << "   4  Thaumaturgy: " << tha << endl;
    cout << endl << endl;
    cout << "Points Remaining: " << lvlskills << endl;
    cout << endl;
    cout << "Enter the number of the skill you wish to increase: ";

    //Applying points to skill attributes

    if(i<=19)
    {
          cin >> input;

          if(input==1)
                str+=1;
          else if(input==2)
               vit+=1;
          else if(input==3)
               agi+=1;
          else if(input==4)
               tha+=1;
          else
               goto nullchoice;

         lvlskills-=1; 
    }    
    i++;
    cout << endl << endl;                     
}

基本上,我正在用C ++创建一个基于文本的RPG游戏。它是相当基本的,你可以从这样的游戏中获得统计数据(力量,活力等)。在开始时,如此处所示,允许玩家将一些点分配给他们选择的技能。

问题出现在哪里。现在,玩家必须输入一个数字(1,2,3或4.如果这些数字都没有,它将转到nullchoice),然后按ENTER键。让玩家这样做是笨拙且完全错误的,所以有什么简单的方法我可以编码,所以他们必须按下这个数字?

我想象我会在游戏剩下的时间里使用它。谢谢你的阅读!

1 个答案:

答案 0 :(得分:0)

您只需存储输入并将其与所需案例进行比较。想一想......

do
{
    system("CLS");
    //Advanced Information
    cout << "Your Statistics: " << endl;
    cout << endl << endl;
    cout << "   1  Strength: " << str << endl;
    cout << endl;
    cout << "   2  Vitality: " << vit << endl;
    cout << endl;
    cout << "   3  Agility: " << agi << endl;
    cout << endl;
    cout << "   4  Thaumaturgy: " << tha << endl;
    cout << endl << endl;
    cout << "Points Remaining: " << lvlskills << endl;
    cout << endl;
    cout << "Enter the number of the skill you wish to increase: ";

    //Applying points to skill attributes
          char input;
          switch(input=getch()){
              case '1':
                str+=1;
                lvlskills-=1;
                break;
          case '2':
               vit+=1;
               lvlskills-=1;
               break;
          case '3':
               agi+=1;
               lvlskills-=1;
               break;
          case '4':
               tha+=1;
               lvlskills-=1;
         } 
    cout << endl << endl;                     
} while(lvlskills>0);

在您的代码中避免goto,而您可以通过其他选项解决它。这是一个很好的做法..