首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带向量的C++魔术8球

带向量的C++魔术8球
EN

Stack Overflow用户
提问于 2020-06-20 01:50:40
回答 1查看 562关注 0票数 0

我正在尝试将最初使用数组的Magic8Ball程序转换为一个使用向量的程序。给我的任务是把下面的代码带到下面,并对它做一些事情。

  • 使用push_back()函数初始化向量
  • 修改getAnswer()函数的签名和原型
  • 修改getAnswer()函数正文中的代码
  • 删除任何不需要的代码,如答案数量的常量。
代码语言:javascript
复制
    #include <iostream>
    #include <string>
    #include <iomanip>
    #include <string>
    #include <stdio.h>
    #include <fstream>
    #include <stdio.h>


    using namespace std;

    string getAnswer();


    const string exitString = "x";
    const int SIZEOF_ANSWERS = 8;
    string magicEightBallAnswers[SIZEOF_ANSWERS] = { "Yes", "No", "Maybe", "It's not certain", "The outlook is good",
                                                     "The outlook is poor", "Time will tell", "Most likely" };



    int main(int argc, char *argv[])
    {
        bool keepGoing = true;

        while (keepGoing)
        {
            string question;

            //prompt for and get the question
            cout << "What is your question?  (Enter 'x' to exit)" << endl;
            getline(cin, question);

            //this assumes that the user enters a lower case x
            if (question.compare(exitString) == 0)
                keepGoing = false;
            else
            {
                cout << getAnswer() << endl;
            }   
        }

        return 0;
    }


    string getAnswer()
    {
        int index = rand() % SIZEOF_ANSWERS;
        return magicEightBallAnswers[index];
    }
EN

回答 1

Stack Overflow用户

发布于 2020-06-20 02:19:32

这个例子可能会有所帮助:

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

string getAnswer(vector<string> &  magicEightBallAnswers)
{
  int i = rand() % magicEightBallAnswers.size();
  return magicEightBallAnswers[i];
}

int main()
{
  vector<string> magicEightBallAnswers {
    "Yes",
    "No",
    "Maybe",
    "It's not certain",
    "The outlook is good",
    "The outlook is poor",
    "Time will tell",
    "Most likely"
  };

  // Initialize rand()
  srand(time(NULL));

  string question;
  while (true) {
    // Prompt for and get the question
    cout << "What is your question?  (Enter 'x' to exit)" << endl;
    getline(cin, question);
    if (question == "x")
      break;

    // Ask question
    cout << getAnswer(magicEightBallAnswers) << endl;
  }

  // Done
  cout << "Bye!  Let's play again soon!" << endl;
  return 0;
}

具体地说:

  • 利用C++特性来消除不必要的代码,如"push_back()“或"(8)”初始化。
  • 如果有像“SIZEOF_ANSWER()”这样的动态选项,千万不要使用像“vector.size”这样的硬编码常量。
  • 注意参照通过:in string getAnswer(vector<string> & magicEightBallAnswers)的用法。
  • 在使用"rand()“之前,应该用种子调用"srand()”。
  • 等。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62480746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档