我正在尝试将最初使用数组的Magic8Ball程序转换为一个使用向量的程序。给我的任务是把下面的代码带到下面,并对它做一些事情。
#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];
}发布于 2020-06-20 02:19:32
这个例子可能会有所帮助:
#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;
}具体地说:
string getAnswer(vector<string> & magicEightBallAnswers)的用法。https://stackoverflow.com/questions/62480746
复制相似问题