Hi everyone, I just started learning C++ from YouTube a few days ago. I wanted to test what I've learned so far.
I wanted to make a program that asked the user to input the number of people in their family, then ask if what they entered was correct. Then eventually I would tell the user the average age of the family. So here's my problem...
int fam, yon, age, agetot, stopper ;
char Y, y;
agetot =0;
stopper=0;
cout << "This program will determine your family's average age.\n";
cout << "How many people are in your family?\n";
cin >> fam ;
cout << "There are " << fam << " people in your family. Is this correct? Press Y for yes, N for no.\n";
cin >> yon;
if ((yon==Y) || (yon==y));{
cout << "Enter a family member's age, then press enter.\n";
}
while (stopper <= fam){
cin >> age;
agetot= agetot + age;
stopper++;
};
cout << "Your family's age total is " << agetot << endl;
Everything works fine up until the point where the user is supposed to enter the family member's age. Then it wont let anything be typed in and outputs "Your family's age total is 0."
Whats the problem here? Thanks for all help.
Have you initialized age with any value before you try to compare it with fam (which I'm guessing has a user input value already?)
Also - I'm not sure that makes sense logically. If fam is the number of family members, let's say 4, would you want to compare someone's age with the number of people in the family?
if ((yon=='Y') || (yon=='y')); <- remove the semicolon here
You may need to clear the cin buffer between receiving the char input and the int input of the ages.
1 2
cin.clear();
cin.ignore();
What if they say the number they entered is not correct?
Edit: If you edit your post, highlight your code, then click on the <> button in the format palette on the right side, your code will format on the forum.
It's not a compiler error but it would probably cause a logic error. That ends the if condition right there. Presumably you want the next line or block of code {} to run only if the if condition is met. With the if statement ended early, the next line or block of code would run regardless of the condition in the if.
int fam, yon, age, agetot, stopper ;
char Y, y;
cout << "This program will determine your family's average age.\n";
cout << "How many people are in your family?\n";
cin >> fam ;
cout << "There are " << fam << " people in your family. Is this correct? Press Y for yes, N for no.\n";
cin >> yon;
if ((yon==Y) || (yon==y)){
cout << "Enter a family member's age, then press enter.\n";
agetot =0;
stopper=1;
while (stopper <= fam){
cin >> age;
agetot= agetot + age;
stopper++;
}};
cout << "Your family's age total is " << agetot << endl;
Wildblue, thank you bro, you're the best! Now that I'm thinking about it, it makes a lot more sense that way. And there was no need to clear the cin buffer. I appreciate your help immensely!