strcmp or string::compare?
For C++, use std::string
and compare using string::compare
.
For C use strcmp
. If your (i meant your programs) strings (for some weird reason) aren't nul
terminated, use strncmp
instead.
But why would someone not use something as simple as ==
for std::string
?
String comparison using '==' or '===' vs. 'strcmp()'
The reason to use it is because strcmp
returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
===
only returns true
or false
, it doesn't tell you which is the "greater" string.
C string comparison
Because in C you have to use strcmp
for string comparison.
In C a string is a sequence of characters that ends with the '\0'
-terminating byte, whose value is 0.
The string "exit"
looks like this in memory:
+-----+-----+-----+-----+------+
| 'e' | 'x' | 'i' | 't' | '\0' |
+-----+-----+-----+-----+------+
where 'e' == 101, 'x' == 120, etc.
The values of the characters are determined by the codes of the ASCII Table.
&command != "exit"
is just comparing pointers.
while(strcmp(command, "exit") != 0);
would be correct. strcmp
returns 0 when both strings are equal, a non-zero
value otherwise. See
man strcmp
#include <string.h>
int strcmp(const char *s1, const char *s2);
DESCRIPTION
The
strcmp()
function compares the two stringss1
ands2
. It returns an integer less than, equal to, or greater than zero ifs1
is
found, respectively, to be less than, to match, or be greater thans2
.
But you've made another error:
scanf("%c", &command);
Here you are reading 1 character only, this command
is not a string.
scanf("%s", command);
would be correct.
The next error would be
char command[4];
This can hold strings with a maximal length of 3 characters, so "exit"
doesn't
fit in the buffer.
Make it
char command[1024];
Then you can store a string with max. length of 1023 bytes.
In general, of want to save a string of length n
, you need a char
array of
at least n+1
dimension.
C++ - using strcmp to compare which name comes first in alphabetical order
All you need to do is return name < per->name;
and be done with it since <std::string>
allows for that comparison and it is the preferred method.
For completeness you could fix your code:
bool Person::lessThan(const Person* per) const {
return strcmp(this->name.c_str(), per->name.c_str()) < 0;
}
@Retired Ninja
Can strcmp() work with strings in c++?
Don't use strcmp
. Use std::string::compare
which has the same behavior as strcmp
.
if(ob[i].getBrand().compare(ob[j].getBrand()) > 0)
Or much better
if(ob[i].getBrand() > ob[j].getBrand())
Generally you should use std::string::compare
when you have to test various cases where the strings will be different, e.g.
auto cmp = ob[i].getBrand().compare(ob[j].getBrand());
if(cmp == 0) ...
else if(cmp > 0) ...
else if(cmp < 0) ...
In this way you only have to do the comparison operation on the strings once.
However, in your case where it's somehow apparent that you only have to use the comparison result in a single case (I'm really assuming, as I don't know the context of the code given), then operator >
will suffice, and is much easier on the eye (the brain!).
Why use strcmp instead of == in C++?
strcmp
compares the actual C-string
content, while using ==
between two C-string
is asking if these two char
pointers point to the same position.
If we have some C-string
defined as following:
char string_a[] = "foo";
char string_b[] = "foo";
char * string_c = string_a;
strcmp(string_a, string_b) == 0
would return true
, while string_a == string_b
would return false
. Only when "comparing" string_a
and string_c
using ==
would return true
.
If you want to compare the actual contents of two C-string
but not whether they are just alias of each other, use strcmp
.
For a side note: if you are using C++
instead of C
as your question tag shows, then you should use std::string
. For example,
std::string string_d = "bar";
std::string string_e = "bar";
then string_d == string_e
would return true
. string_d.compare(string_e)
would return 0
, which is the C++
version of strcmp
.
What does strcmp return if two similar strings are of different lengths?
It returns the difference at the octet that differs. In your example '\0' < '2'
so something negative is returned.
How to use functions of strings.h like strcmp() with object of string.h in c++
strcmp
operates on c-strings, not std::strings.
To access the internal c-string of an std::string, use the c_str() method.
i.e.
if (strcmp(a.c_str(), b.c_str()) == 0) {
// ...
}
But you can also do the comparison directly
if (a == b) {
// ...
}
Problems with the comparison of two strings using strcmp
Your compiler gives you an error because strcmp
is a C-style function that expects arguments of type const char*
and there is no implicit conversion from std::string
to const char*
.
And although you might retrieve a pointer of this type using std::string
's c_str()
method, since you are working with std::string
objects, you should use the operator ==
instead:
if (ligne == ligne_or) ...
or comparison with const char*
:
if (ligne == "[Syn****]") ...
Related Topics
Why Can't I Use <Experimental/Filesystem> with G++ 4.9.2
Should I Include Stddef.H or Cstddef for Size_T
Is It Legal to Modify the Result of Std::String::Op[]
How to Implement "_Mm_Storeu_Epi64" Without Aliasing Problems
Stl Container with Std::Unique_Ptr's VS Boost::Ptr_Container
Error C1083: Cannot Open Include File: 'Stdafx.H'
Why Does (I|O)Fstream Take a Const Char* Parameter for a File Name
Sorting a List of a Custom Type
Does Gdi+ Have Standard Image Encoder Clsids
Where Does the _1 Symbol Come from When Using Llvm's Libc++
Boost Libraries in Multithreading-Aware Mode
Purpose of Perfect Forwarding for Callable Argument in Invocation Expression
Const and Non Const Template Specialization
Is Updating Double Operation Atomic
Google Mock - How to Call Expect_Call Multiple Times on Same Mock Object
Is There Any Automated Way to Implement Post-Constructor and Pre-Destructor Virtual Method Calls
Subtraction of Two Nullptr Values Guaranteed to Be Zero
Why How to Call a Non-Constexpr Function Inside a Constexpr Function