0

i get this error when i try executing it,

no match for the operator ==

now i understand you can't compare a string with a char, so i tried other method like strcmp, covert a to char, but none worked.

note: coverting d to string is not an option.

#include <iostream>
#include<string>

using namespace std;

int main(int argc, char *argv[])
{
    int i;
    char d='h';    
string s="this is a string";
string a;
a=s.substr(1,1);
if(a==d)  
cout<<"String compared\n";

cout<<a<<"\t"<<s<<"\n";
cin>>i;

    return 0;
}
4
Contributors
4
Replies
19
Views
4 Months
Discussion Span
Last Post by AssertNull
1

So the best place to post this was the Community Center?

Votes + Comments
For some reason, no match for operator sounds spot on here. Hope they find their way around the forums.
0

You should describe what you're TRYING to do in simple English sentences. I'm guessing here, but it LOOKS like you MAY be trying to test whether the character at index 1 of "this is a string" is the letter 'h'. If so...

#include <iostream>
#include<string>
using namespace std;

int main(int argc, char *argv[])
{
    char d='h';    
    string s="this is a string";
    if(s[1]==d)  
        cout<<"The character at index 1 is 'h'" << endl;
    return 0;
}

If this is NOT what you are trying to do, please explain what you are trying to do. But the compiler sees a string and a character and can't guess what you want. Hence the error.

0

You can also create a string from the char variable d and compare two strings, as so...

#include <iostream>
#include<string>

using namespace std;

int main(int argc, char *argv[])
{
    char d='h';    
    string s="this is a string";
    string a = s.substr(1,1);
    if(a==string(1,d))  
        cout<<"The character at index 1 is 'h'" << endl;
    return 0;
}

string(1,d) creates the string "h" from the character 'h'. See http://www.cplusplus.com/reference/string/string/string/

Look at constructor #6, the "fill" constructor.

string (size_t n, char c);
Fills the string with n consecutive copies of character c.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.