1

Is this comparison possible to do in C++?

std::string name = "John";

if (name == "Tom")
   flag = true;
else
   flag = false;
3
  • 7
    Why not flag = name == "Tom";?? Commented Jan 16, 2013 at 14:25
  • Yes, you can. Commented Jan 16, 2013 at 14:33
  • 2
    @KerrekSB: I personally would use flage = (name == "Tom"); Commented Jan 16, 2013 at 14:46

2 Answers 2

13

Yes it is, because std::string overloads operator == for const char*.

Alternatively, you can just write

flag = name == "Tom";

or use std::string::compare (returns 0 if the strings match)

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

Comments

-7

To compare srtings in c++, I recommend you to use STRCMP from:

#include <string.h>
....
STRCMP(name,"Tom"); // This will return 0 if they are equal

so you should use it as:

if (STRCMP(name,"Tom")==0)
  flag = true;
else
  flag = false;

remember to use #include < string.h>

7 Comments

Why would be better an old fashioned function or macro or wathever STRCMP is than the std::basic_string comparision operators?
there is no such thing as STRCMP in standard C++.
@Sascuash: it seems to me that most people find op== more human friendly, also given that if he meant strcmp from C, the call would look different (besides that it is more inefficient and can even lead to wrong results, depending on the contents of name)
@Sascuash: not at all, I personally can clearly distinguish = and ==. And if you can not, you can still write if(name=="Tom"). And even if it was, this still does not resolve the cases where both lead to different results.
@Sascuash, first, STRCMP is a macro, defined (if I remember correctly) for Windows C++ libraries (i.e. not standard C++). Second, please don't recomment C string processing functions in C++ - they lead to bad/unsafe C++ coding and miss the advantages of modern C++ code (RAII comes to mind). String comparisons in C++ should be made using std::string (that is the reason std::string is there for).
|

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.