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 ?"....
9 Answers
+ 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;
}
+ 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;
}
+ 2
Use string for text, and int for numbers.
+ 2
endl is to put a line break. Use it when needed.
0
oh yes with "==" "1" and "2" work ! but i can t use "yes" and "no" ?
0
if i want to put 3 answer when i use the "else" always at the end ?
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"
0
but i can delete the "<< endl" and its always work. Is better to write it anyway ?
0
Ok, thank you for all you answers it's really help me !