0
Can we compare string datatype with char datatype
#include <iostream> #include<string> using namespace std; int main() { char c='a'; string x="a"; if(x==c) cout<<"true"<<<endl; else cout<<"false"<<endl; return 0; }//Is this code correct
3 Answers
+ 1
Well yes and no. You cannot directly compare different types like this in c++ since it is a strongly typed language. You can convert types or use the bracket notation to address your first letter in your string receiving a char.
try if(x[0]==c)
+ 1
only if your string can be cast down to a char, unless your string is actually a char length long can you compare these, otherwise you can not. String "c" in cstrings can be 'c' which you can then cast to a char and comparing "c" casted to a char would yield the same as 'c' note that giving an index to a string will yield the indexed char like string mychar="char" using cstrings mychar[0] == 'c' which you can compare to char c = 'c' and logically these are equivalent.
+ 1
Yes You Can Compare Char with String As Char supports Implicit Conversion to String datatype. Hence, We can Compare Char with String datatype
Also Type Casting Can be done From Char to String.
Thank you!