murtu52 Posted March 5, 2005 Report Share Posted March 5, 2005 Well, I'm learning C++, and i am writing a program i saw on one of the tutorials. Basically, if you are younger than 50, it'll say you are young, if you are older than 50, it'll say you are old (I had to take out the if "age==50" to see if that was the problem or not; it isn't, and i don't want to put it back in because i'm afraid it'll mess up even more. Here is my source code:#include <iostream>using namespace std;int main(){ int age; cout<<"Please enter your age \n"; cin>> age; cin.ignore(); if (age>50){ cout<<"You are old!\n";} else (age<50);{ cout<<"Wow, you are young!\n";} cin.get();}Basically, when i run the program, and say i'm older than 50 (For instance, i enter i'm 60) it prints both "You are old!" and "Wow, you are young!" My dad helped me figure out that it is ignoring the "else (age<50)" statement and printing the "Wow, you are young!" part, if the "if (age>50)" statement was true. Anyone have any thoughts? I can't see any problems with it, but then again, i'm a beginner...... Quote Link to post Share on other sites
jcl Posted March 5, 2005 Report Share Posted March 5, 2005 (edited) Common error. Your problem is in the 'else' branch of the conditional. This:else (age<50); { cout <<"Wow, you are young!\n";}is equivalent to this:else { (age<50);}{ cout << "Wow, you are young!\n"}What you have there is the single-statement (blockless) version of 'else' followed by a block with some deceptive formatting. You probably want:else if (age<50) { cout << "Wow, you are young!\n"}or perhaps:else { cout << "Wow, you are young!\n"} Edited March 5, 2005 by jcl Quote Link to post Share on other sites
Matt Posted March 5, 2005 Report Share Posted March 5, 2005 I'm also in the learning stage of C++, but I would also suggest what jcl said as in:else { cout << "Wow, you are young!\n"}because the other statement says that if they are over 50, to display "they are old" or something, all you need now is a statement for if they are NOT over 50, you do not have to defign what "not over 50" is (when you said if (age<50) ) that was not needed.Hope that helpsMatt Quote Link to post Share on other sites
murtu52 Posted March 6, 2005 Author Report Share Posted March 6, 2005 Thanks, just wanted to clear that up....I think i'm gonna need a whole lot more help if i'm ever gonna master this language.... Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.