0

Why my program doesn t work ?

#include <iostream> using namespace std; int main() { int answer; cin >> answer; if (answer=yes) { cout << "ok"; } if (answer=no) { cout << "why ?"; } return 0; } So, where is the problem ? thx ! If i put "1" and no "yes" and "2" and not "no" i when i write the answer whatevers if i write "1" or "2", the output is "okwhy ?"....

27th Oct 2016, 10:08 AM
Olivier L'olivier sacré
Olivier L'olivier sacré - avatar
9 ответов
+ 3
= is the assignment operator. Use == to check for equality. Also, yes and no aren't defined. I suppose you meant to use the strings "yes" and "no". In that case, you should also change the type of answer to string. #include <iostream> using namespace std; int main(){ string answer; cin >> answer; if (answer == "yes") { cout << "ok" << endl; } else if (answer == "no") { cout << "why?" << endl; } return 0; }
27th Oct 2016, 10:14 AM
Zen
Zen - avatar
+ 2
It's better to use an else here since if answer is "yes", you don't have to check if it it "no" later in the execution that way. You can also use a switch if you have more answers. The synthax isn't really lighter, but at least you can see right away that the whole block is about testing the value of answer. switch(answer){ case "yes": cout << "ok" << endl; break; case "no": cout << "why?" << endl; break; case "maybe": cout << "make your choice already" << endl; break; default: cout << "I didn't get your answer" << endl; }
27th Oct 2016, 10:32 AM
Zen
Zen - avatar
+ 2
Use string for text, and int for numbers.
27th Oct 2016, 10:36 AM
Zen
Zen - avatar
+ 2
endl is to put a line break. Use it when needed.
27th Oct 2016, 11:02 AM
Zen
Zen - avatar
0
oh yes with "==" "1" and "2" work ! but i can t use "yes" and "no" ?
27th Oct 2016, 10:18 AM
Olivier L'olivier sacré
Olivier L'olivier sacré - avatar
0
if i want to put 3 answer when i use the "else" always at the end ?
27th Oct 2016, 10:24 AM
Olivier L'olivier sacré
Olivier L'olivier sacré - avatar
0
yes it's perfectly work with "string answer" and i don t need to use "else" thank you ! but when use "string" and when "int"
27th Oct 2016, 10:33 AM
Olivier L'olivier sacré
Olivier L'olivier sacré - avatar
0
but i can delete the "<< endl" and its always work. Is better to write it anyway ?
27th Oct 2016, 10:39 AM
Olivier L'olivier sacré
Olivier L'olivier sacré - avatar
0
Ok, thank you for all you answers it's really help me !
27th Oct 2016, 11:04 AM
Olivier L'olivier sacré
Olivier L'olivier sacré - avatar