问题
I'm trying to take a Magic 8 Ball program that was originally using arrays and change it to a program that uses vectors instead. The task that I was given was to take the code below and do a couple of things to it.
- use the push_back() function to initialize the vector
- modify the signature and prototype of the getAnswer() function
- modify the code in the body of the getAnswer() function
- remove any unneeded code, such as your constant for the number of answers
#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];
}
回答1:
This example might help:
#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;
}
Specifically:
Use C++ features to your advantage, to eliminate unnecessary code like "push_back() or initializing with "(8)".
Never use a hard-coded constant like "SIZEOF_ANSWER" if there's a dynamic alternative like "vector.size()".
Note the use of pass by reference: in
string getAnswer(vector<string> & magicEightBallAnswers)
.You should call "srand()" with a seed before using "rand()".
Etc.
来源:https://stackoverflow.com/questions/62480746/c-magic-8-ball-with-vectors