I'm trying to make a quiz checker where the user will input their answer and it will automatically check in the array. Any tips?
Here is my code:
int main()
{
string aswer[] = { "D", "C", "D", "D", "A"); //
char input[5];
int counter ;
int points = 0;
cout << "Welcome and Good luck!\n";
for (counter = 0; counter < 5; counter++) {
cout << counter << " Choose from letters A-D: \n";
cin >> input;
}
for (int i = 0; i < 5; ++i) {
cout << "\n you enter " << input[i] << endl;
}
foreach (char item in answer){
foreach (char item1 in inputs){
If (item == item1){
points = points +1
}
}
}
return 0;
}
Tips -- be consistent choosing storage. If you are using a
std::stringfor theanswer(not the erroneous array ofstd::stringshown), then use astd::stringforinputas well. But if you must use a POA (plain old array), that's fine for educational purposes -- you just lack all auto-memory management and bounds protections.You initialize a std::basic_string as:
(note: the use of
std::namespace identifier. See Why is “using namespace std;” considered bad practice?)Don't use Magic Numbers in your code. The
5you stick in your array declaration and in your loop limit is a Magic Number. Instead,When you loop taking input, validate every input. The user may well generate a manual
EOFto cancel input with Ctrl+d (or Ctrl+z on windows). Only increment the count of characters stored after you have validated the input, e.g.For your output, understand the difference between using
'\n'andstd::endl, C++: “std::endl” vs “\n”.When you have items stored in a container (such as
std::string), you can use a Range-based for loop (since C++11) to loop over each item in the container. To loop over your stored input, you must limit the loop to the number of elements successfully read as input. Use the samecounteras your comparison limit, e.g.Putting it altogether, you would have:
Example Use/Output
Checking maximum points if all characters match:
Look things over and let me know if you have questions.