1

I am getting a weird problem in comparing two string in c++.

c pointing to "dreamy" , which I have confirmed from the printf statement. Now I want to compare this with "dreamy" string but every time it is going in else part and showing not matching.

cout statement of both Str1 and Str2 also printing same output "dreamy" but the length of Str1 is showing 7 and length of Str2 is 6.

Can anybody tell me what is the problem and how to fix it.

Thanks.

        char *c;
        c = strtok (temp,",");   
                    // Here   printf ("%s\n",c);   prints    dreamy
        while (c != NULL)
        {
            std::string Str1 = std::string(c);
            std::string Str2 = std::string("dreamy");
            cout << "Str1  " << Str1 << "Len" << Str1.length() <<endl;  //  Len = 7 showing for  c = "dreamy"
            cout << "Str2  " << Str2 << "Len" << Str2.length() <<endl;  //  Len = 6 for "dreamy"
            if(Str1.compare(Str2) == 0)
            {
                cout << "Finally Match";
                presence[1] = 1;
            }
            else
                cout << " Dont Match";
            printf ("%s\n",c);
2
  • What's in temp? And please show the exact output of your cout << statements. Commented Apr 12, 2013 at 11:35
  • NPE answer helped me. There was a space after "dreamy " after strtok Commented Apr 12, 2013 at 11:43

1 Answer 1

3

Len = 7 suggests there's a spurious character in the first string (perhaps a space or a newline).

Sign up to request clarification or add additional context in comments.

1 Comment

That's why I like to print string using cout << '[' << str << ']' :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.