Hello Everyone :)
I am a beginner in c++ so i dont have much knowledge. I recently saw the tutorial video of "if-else statement" and everything worked fine when i was making a simple program. But why cant i express words in if statement?
Like:
#include<iostream>
usingnamespace std;
int main ()
{
int a;
char finish;
cout<<"Please type finish to end this program"<<endl;
cin>>a;
if (a==finish)
{ cout<<"Thank u for using our program"<<endl;
}
else
{ cout<<"Please type finish only"<<endl;
}
}
Now when I compile and run it, whenever i type any letter like a, b, c or any letter, it says"Thank You for using our program" which i stated if a=finish only. But when i type any number lilke 1,2 etc then i get the else statement.
so is there any way i can express words in if statement?
You are putting what the user types in into an integer, which will not work. If you want the user to actually type the word "finish", then change a to be a string. Also, change the variable "finish" to also be a string and set the variable to the word "finish":
Line 9: a is an int. You can't store a a word in an int.
Line 6: finish is a n uninitialized character (it has a garbage value).
Line 10: You're trying to compare an int to an uninitialized character.
You want something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{ string answer;
cout<<"Please type finish to end this program"<<endl;
cin >> answer;
if (answer == "finish") // note the quoted string literal
{ cout<<"Thank u for using our program"<<endl;
}
else
{ cout<<"Please type finish only"<<endl;
}
}
Note: You probably want a loop in order to ask for the answer again if the answer is not "finish".