I got a problem when processing 2D array. This program is supposed to repeatedly prompts the user to enter a capital for a province. Upon receiving the user input, the program reports whether the answer is correct. Set up the capitals for the provinces in a two-dimensional array. The program prompts the user to enter ten province capitals or when the user enters “QUIT” as an answer. Before your program terminates, display the total correct answers.
Here's my code:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Guess the Capital of the Province!" << endl << endl;
string key[2][10] =
{
{"Ontario", "Quebec", "Manitoba", "New Brunswick", "British Columbia", "Prince Edward Island", "Saskatchewan", "Alberta", "Newfoundland and Labrador", "Nova Scotia"},
{"Toronto", "Quebec City", "Winnipeg", "Fredericton", "Victoria", "Charlottetown", "Regina", "Edmonton", "St. John's", "Halifax"}
};
int correct = 0;
string ans;
for (int col = 0; col < 10; col++) {
cout << "What is the capital of " << key[0][col] << "?" << endl;
cin >> ans;
if (ans == key[1][col]) {
correct++;
cout << "Your answer is correct." << endl << endl;
} else if (ans == "QUIT") {
break;
} else {
cout << "Your answer is incorrect." << endl;
}
}
cout << "Total Correct Answers: " << correct << endl;
return 0;
}
When I run it, it got an error:
What is the capital of Quebec?
Quebec City
Your answer is incorrect
What is the capital of Manitoba?
Your answer is incorrect
What is the capital of New Brunswick?
without storing user input for capital of Manitoba. And also, it doesn't increment the variable correct if user got the answer right for the last question.
I wonder why these things happened as I believe my algorithm is on track. Thanks for your help.
Aucun commentaire:
Enregistrer un commentaire