0
I don't understand what's wrong
This is a part of my code. The problem is that it works but not correctly. As an output it shows ya = 1 even when actually you declare it with a different value. int ya; string YA; cout << "Your Age:"; cin >> ya; if(ya < 0){ cout << "Invalid value"; return 0; } else if (ya >= 0) { if (ya = 0) { string YA = " "; } else if (ya = 1) { string YA = "year old"; else { string YA = "years old"; } cout << ya << YA << endl << endl << endl; }
11 Answers
+ 8
in the if statement your not using the initial string, your making a new one.
YA = ""; Not string YA =...
Also missing: } after checking if the age is equal to 1.
+ 23
I think redeclaration of string YA is causing the problem. After the 1st "string YA", replace every "string YA" with only "YA".
+ 23
Inside each if block, if you redeclare a variable YA, it'll be considered as different YA. We can't access it outside the if block. So when you were printing YA at last line, it was referring the 1st YA, which was empty initially.
+ 22
Compare equality using == as follows :
if(ya==0)
else if (ya==1)
+ 3
I see. I learnt something new. Something that I wouldn't learn it via courses. Coding yourself is the best course.
+ 1
Thanks! Now it works! So I guess you must write only the name of the variable after you call it as string.
+ 1
string is not a data type
its declaration is as
char[]="ya";
+ 1
and to print
cout<<YA;
0
I just did that and it doesn't show the value of string variable.
0
Like any variable right?
0
مرحبا