user1355603
user1355603

Reputation: 305

How to make strings equal?

In this a and "v1" does not come out to be equal...although the content is same..can someone help in suggesting a way such that a comes out to be equal to "v1"

int main()
{
    stringstream s;
    string a;
    char *c="v1";
    s<<c;
    a=s.str();
    cout<<a;
    int i=strcmp(a, "v1");
    cout<<"i="<<i;
}

On comparing a and "v1" do not come out to be equal...please suggest some way such that i may make a to be equal to "v1"...the end goal is to make a to be equal to "v1".

Upvotes: 0

Views: 408

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272822

Because strcmp returns 0 when the inputs match.

(Incidentally, I assume that your actual code is strcmp(a.c_str(), "v1"), because otherwise it wouldn't have compiled.)

Upvotes: 6

John Dibling
John Dibling

Reputation: 101506

They are the same, at least lexically. Note that strcmp returns 0 when the strings are the same, which is not the same as true.

int main()
{
    stringstream s;
    string a;
    const char *c="v1";
    s<<c;
    a=s.str();
    cout << a << "\t" << c;
    cout << endl;
    cout << boolalpha << (a == c) << endl;
    cout << boolalpha << (!strcmp(c, a.c_str())) << endl;
}

Output:

v1      v1
true
true

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57749

strcmp requires a char *, where as a is of type std::string.

The std::string class provides a method that returns a format compatible with strcmp.
Try: int i = strcmp(a.c_str(), "v1");

Upvotes: 0

Related Questions