Can we compare string datatype with char datatype | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

28th Nov 2016, 6:02 PM
prasanth pra
prasanth pra - avatar
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)
28th Nov 2016, 6:58 PM
ordens
ordens - avatar
+ 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.
29th Nov 2016, 3:40 AM
Eric Gitangu
Eric Gitangu - avatar
+ 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!
6th Dec 2016, 3:22 PM
Dharamveer Gupta
Dharamveer Gupta - avatar