【问题标题】:comparing 1d array to users input?将一维数组与用户输入进行比较?
【发布时间】:2012-02-08 06:13:20
【问题描述】:

我正在编写一个测验程序。我有一个来自文本文件的正确答案的一维数组,我必须将其与users_guess 进行比较以检查他的猜测是否正确。我必须随机吐出 6 个问题。

string questions[50];  // 50 questions
char answers[50]; // 50 correct answers
int i = 0;
char user_guess;

int rand_index = rand() % 10; //generate random number

for (i=0; i<6; i++)      //loop for 6 questions
{    
cout << questions[rand_index] << endl;
questions[rand_index] = answers[] // i need help. how do i compare the arrays?
cin >>  user_guess;
    if (user_guess != answers[]) // if he's wrong
    { 
    cout << "sorry. try again" << endl;
    cout << questions[rand_index] << endl;  // 2nd chance
    cin >> user_guess;
        if (user_guess!= answers[]) // wrong again
        {
        cout << "you lose.game over." << endl; //game over
        break;  // does this cancel the game all together?

        }
        else
        {
        cout << "good job!" << endl;
        i++;   // on to the next round
        }
    }
    else
    {
    cout << "good job!" << endl;
    i++;   // on to the next round
    }
}

我的麻烦是将一系列问题与一系列答案联系起来。另外,如果他错了两次,就结束程序。大家觉得呢?

【问题讨论】:

  • 好的,所以你想从 50 个问题中随机抽取 6 个问题,一一提出,如果用户两次都错了就结束程序,否则继续直到他回答 6?
  • 你应该问问你的老师。这就是他的目的。至于比较数组,您需要一次比较一个项目;很遗憾,您无法比较整个数组。
  • 好吧,这有帮助。我可以在数组中读取更多内容,以便一次比较它们。
  • 我实际上是自己做的。我哥哥说这个项目真的帮助他在编码方面做得更好。他在大学里做到了。我只有 14 岁,我想向他展示我很好。

标签: c++ arrays random numbers


【解决方案1】:
Here's a hint:

// ...
{
   const string &the_question = questions[rand_index];
   const char &the_answer = answers[rand_index]; // using a const char & 
                                                 // is a deliberate pedantism


   cout << the_question << endl;
   char user_guess;
   cin >> user_guess;
   if (the_answer != user_guess) { 
   ...
   }

注意:在完成好工作后你会增加一次,然后在 for 循环中再增加一次,所以你会以二为单位计数。

【讨论】:

  • 好的,所以声明 2 const .. 传递 the_question 和 the_answer 允许我将它们用作随机数...我明白你在说什么
  • 在第一个版本中,您将问题和答案直接放入程序中。一旦您从打印问题和获得答案中找出所有错误,您就可以转到第二个版本。在第二个版本中,您有两个文件,一个有 50 个问题,另一个有 50 个答案。你通过读取这两个文件来加载你的数组。当您从中消除错误时,您将进入第三个版本。这使用一个文件,问题和答案交替出现。您可以通过读取交替行来加载数组。最后一个版本,文件中可以有任意数量的q&a。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多