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; }

19th Apr 2017, 8:07 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
11 ответов
+ 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.
19th Apr 2017, 8:30 PM
Rrestoring faith
Rrestoring faith - avatar
+ 23
I think redeclaration of string YA is causing the problem. After the 1st "string YA", replace every "string YA" with only "YA".
19th Apr 2017, 8:26 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 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.
19th Apr 2017, 8:34 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 22
Compare equality using == as follows : if(ya==0) else if (ya==1)
19th Apr 2017, 8:18 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 3
I see. I learnt something new. Something that I wouldn't learn it via courses. Coding yourself is the best course.
19th Apr 2017, 8:36 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
+ 1
Thanks! Now it works! So I guess you must write only the name of the variable after you call it as string.
19th Apr 2017, 8:30 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
+ 1
string is not a data type its declaration is as char[]="ya";
25th Apr 2017, 4:18 AM
Mayank sahu
Mayank sahu - avatar
+ 1
and to print cout<<YA;
25th Apr 2017, 4:20 AM
Mayank sahu
Mayank sahu - avatar
0
I just did that and it doesn't show the value of string variable.
19th Apr 2017, 8:22 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
0
Like any variable right?
19th Apr 2017, 8:31 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
0
مرحبا
19th Apr 2017, 9:12 PM
محمد علي