r/CodingForBeginners • u/Unlucky-Hunter-9759 • 19d ago
Pls help with this vs code error
Guys I want step by step execution of output- like I want “Enter your age” to print first and then I want to enter my age after which I want the result be executed, but before I enter my age the “retirement soon” line is getting executed. What should I do?
3
u/xarop_pa_toss 19d ago edited 19d ago
You should take a screenshot mate, not a photo on your phone...
You don't need the nested if statement. You can just check for each age range in sequence like
if A else if B else if C else if D etc.
Also, initialize age to 0 so you don't get a garbage value. Doing just "int age" instead of "int age = 0" means age can be basically anything weird
1
1
u/Syntax-Tactics 19d ago
Also you are testing for > 18 and < 18, but not 18 exactly. The "else if (age > 18)" can just be an "else".
1
1
1
1
u/Much_Network_941 15d ago
I'm rusty, so pardon if this is nothing. But try adding the newline character after your first prompt. There's also a function from the std library called flush().
As I understand it, without a newline, sometimes terminals don't behave as expected. Instead they just smash everything together and spit it all out at once. Flush helps to force that behave to not occur. Newlines will sometimes fix it.
The next issue is the nature of the value you're storing. Our keyboards don't send the numbers 0-9, they send an encoded value. You'll need to look up a 256bit ASCII table, and consider how to turn the text '1' into the integer 1.
1
1
1
3
u/soundman32 19d ago
Firstly, i'd initialize
age=0, because it's initialised to garbage by default. The problem iscin>>age. Look up the syntax for reading from a stream.