'How can I get my counter to work properly?
I'm doing my c++ homework on arrays, everything seems to be working fine except the counter for the problem. Before I show the code these are the requirements for the question
- create an array of 10 yes or no questions
- prompt user to enter yes or no, yes being 'Y' or 'y'. anything else being no
- Print back the number of yes'
- Give a rank based on amount of yes'
This is what my code looks like
#include <iostream>
#include <string>
using namespace std;
int main()
{
//variables
int i, yes;
char choice;
string mastery;
//declare array of questions
string quiz [10] = {
"1. Have you been gaming for more than three years? ", "2. Have you ever dressed as a videogame character for halloween? ", "3. Do you own more than one console? ", "4. Have you stayed up passed midnight to play games? ", "5. Have you ever thrown a controller out of rage? ", "6. Have you ever needed to look up a walk through for a game? ", "7. Do you have a main in a fighting game? ", "8. Ever watched an esports tournament? ", "9. Did you ever own a handheald console? ", "10. Ever had a crush on a character in a game? "
};
//header
cout << "Are you truly a gamer? Take this quiz and find out!" << endl;
cout << endl;
//array
for (i = 0; i < 10; i++)
{
cout << quiz[i];
cin >> choice;
if (choice == 'Y' || choice == 'y')
{
yes = yes + 1;
}
}
cout << endl;
//amount of yes'
cout << "You answered yes " << yes << " times" << endl;
//calculate mastery level
if (yes <=2)
{
mastery = "Novice";
}
else if (yes <= 5)
{
mastery = "Apprentice";
}
else if (yes <= 8)
{
mastery = "adept";
}
else if (yes <= 10)
{
mastery = "Expert";
}
//print mastery level
cout << "Your gamer rank is: " << mastery << endl;
}
This is a sample output I got
Are you truly a gamer? Take this quiz and find out!
1. Have you been gaming for more than three years? y
2. Have you ever dressed as a videogame character for halloween? y
3. Do you own more than one console? y
4. Have you stayed up passed midnight to play games? y
5. Have you ever thrown a controller out of rage? y
6. Have you ever needed to look up a walk through for a game? y
7. Do you have a main in a fighting game? y
8. Ever watched an esports tournament? y
9. Did you ever own a handheald console? y
10. Ever had a crush on a character in a game? y
You answered yes 4821545 times
Your gamer rank is:
I don't know why my counter is not working, would appreciate some feedback and solutions!
Solution 1:[1]
The Fix:
int i = 0;
int yes = 0;
By default, C++ will not initialize your variables. Unless you do it explicitly, they will contain a garbage value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
