473,748 Members | 2,551 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strcmp vs. string::compare (const string &)

Hi,

For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.

Feb 28 '06 #1
10 14485
lc****@yahoo.co m wrote:
For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.


'compare' takes into consideration _all_ contents, including any number
of the "terminatin g" null characters. 'c_str()' effectively truncates
the contents at the first null character.

Try comparing the "size"s of s1 and s2.

V
--
Please remove capital As from my address when replying by mail
Feb 28 '06 #2
lc****@yahoo.co m wrote:
Hi,

For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.


Post a complete program that demonstrates the problem. The one I'll
show below does NOT exhibit that behavior:

#include <string.h>
#include <string>

int main(void)
{
using namespace std; // quick and dirty

string s1 = "foo";
string s2 = "bar";

if (!strcmp(s1.c_s tr(), s2.c_str()))
cout << "match\n";
else
cout << "no match\n";

if (!s1.compare(s2 ))
cout << "match\n";
else
cout << "no match\n";
string s3 = "foo";
string s4 = "foo";

if (!strcmp(s3.c_s tr(), s4.c_str()))
cout << "match\n";
else
cout << "no match\n";

if (!s3.compare(s4 ))
cout << "match\n";
else
cout << "no match\n";

return 0;
}
Results:

no match
no match
match
match

Brian
--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Feb 28 '06 #3
Default User wrote:
lc****@yahoo.co m wrote:

Hi,

For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.

Post a complete program that demonstrates the problem. The one I'll
show below does NOT exhibit that behavior:

#include <string.h>
#include <string>

int main(void)
{
using namespace std; // quick and dirty

string s1 = "foo";
string s2 = "bar";

if (!strcmp(s1.c_s tr(), s2.c_str()))
cout << "match\n";
else
cout << "no match\n";

if (!s1.compare(s2 ))
cout << "match\n";
else
cout << "no match\n";
string s3 = "foo";
string s4 = "foo";


Add

s3.append(5, 0); // add 5 zeros at the end

and see what happens.

if (!strcmp(s3.c_s tr(), s4.c_str()))
cout << "match\n";
else
cout << "no match\n";

if (!s3.compare(s4 ))
cout << "match\n";
else
cout << "no match\n";

return 0;
}
Results:

no match
no match
match
match

Brian


V
--
Please remove capital As from my address when replying by mail
Feb 28 '06 #4
Victor Bazarov wrote:
Default User wrote:
[snip code]

Add

s3.append(5, 0); // add 5 zeros at the end

and see what happens.


I know what would happen. Does the OP? As I said, without seeing the
code he's running, there's no way to tell. Mine was an example of usage
that got different results than he reported. He should use that to
compare with his and see what the differences are.

It could be he's not using one of the routines correctly. It could be
that his strings aren't really equal, perhaps for the reason you
mention. We can't tell.

The ball's in his court. There's really no point in further discussion
without a complete program to analyze.

Mar 1 '06 #5
Victor Bazarov wrote:
lc****@yahoo.co m wrote:
For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.


'compare' takes into consideration _all_ contents, including any number
of the "terminatin g" null characters. 'c_str()' effectively truncates
the contents at the first null character.


Nitpick: it's not c_str() truncating the strings, it's strcmp() only reading
until it finds the first null character.
Best

Kai-Uwe Bux
Mar 1 '06 #6
Kai-Uwe Bux wrote:
Victor Bazarov wrote:

lc****@yahoo. com wrote:
For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.


'compare' takes into consideration _all_ contents, including any number
of the "terminatin g" null characters. 'c_str()' effectively truncates
the contents at the first null character.

Nitpick: it's not c_str() truncating the strings, it's strcmp() only reading
until it finds the first null character.


Where is the guarantee that the pointer 'c_str()' returns in _not_ to some
temporary buffer that only contains characters up to and including the
first null char? Note that if the 'data()' of the std::string does _not_
contain a null char, the string _has_ to create a temporary buffer. So,
it is _most_ likely that the temporary buffer is created. And if it is,
there is no sense for the 'string' to copy anything there beyond the first
null character. Hence, the scenario where the 'string' truncates is as
equally plausible as the one where it doesn't.

V
--
Please remove capital As from my address when replying by mail
Mar 1 '06 #7

Victor Bazarov wrote:
Kai-Uwe Bux wrote:
Victor Bazarov wrote:

lc****@yahoo. com wrote:

For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.

'compare' takes into consideration _all_ contents, including any number
of the "terminatin g" null characters. 'c_str()' effectively truncates
the contents at the first null character.

Nitpick: it's not c_str() truncating the strings, it's strcmp() only reading
until it finds the first null character.


Where is the guarantee that the pointer 'c_str()' returns in _not_ to some
temporary buffer that only contains characters up to and including the
first null char? Note that if the 'data()' of the std::string does _not_
contain a null char, the string _has_ to create a temporary buffer. So,
it is _most_ likely that the temporary buffer is created. And if it is,
there is no sense for the 'string' to copy anything there beyond the first
null character. Hence, the scenario where the 'string' truncates is as
equally plausible as the one where it doesn't.


That was not nitpicking. The standard (well - the draft, but I doubt
this has changed) says about c_str:
-1- Returns: A pointer to the initial element of an array of length
size() + 1 whose first size() elements equal the corresponding elements
of the string controlled by *this and whose last element is a null
character specified by charT().

Also, I doubt that many implementations will allocate a temporary
buffer. Most will just assure that the buffer always has room enough
for one extra character and place a null at size() whenever c_str is
called.

/Peter
V
--
Please remove capital As from my address when replying by mail


Mar 1 '06 #8
peter koch wrote:
[..] The standard (well - the draft, but I doubt
this has changed) says about c_str:
-1- Returns: A pointer to the initial element of an array of length
size() + 1 whose first size() elements equal the corresponding elements
of the string controlled by *this and whose last element is a null
character specified by charT().
You're right, my bad. So, we can safely say that all null characters are
represented in that array and while 'strcmp' does ignore everything after
the first null char it encounters, 'memcmp' should be able to compare them
correctly.
[..]


V
--
Please remove capital As from my address when replying by mail
Mar 1 '06 #9
Victor Bazarov wrote:
Kai-Uwe Bux wrote:
Victor Bazarov wrote:

lc****@yahoo .com wrote:

For two stl strings s1 and s2, I got different results from

strcmp(s1.c_str (), s2.c_str())
and
s1.compare(s2)

can someone explain what these functions do? It seems that strcmp
gives the "right" (i.e.wysiwyg) answer while compare() does not.

'compare' takes into consideration _all_ contents, including any number
of the "terminatin g" null characters. 'c_str()' effectively truncates
the contents at the first null character.

Nitpick: it's not c_str() truncating the strings, it's strcmp() only
reading until it finds the first null character.


Where is the guarantee that the pointer 'c_str()' returns in _not_ to some
temporary buffer that only contains characters up to and including the
first null char?

[snip]

Standard, clause [21.3.6/1].

Best

Kai-Uwe Bux

Mar 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2228
by: Flzw | last post by:
I've been trying to use std::string::compare and apparently it is case sensitive, I searched the net but I can't find a way for it not to take case into account, the solution I have for now is using stricmp with s1.c_str() and s2.c_str() but I assume there is a better way... Thanks.
11
11464
by: xuatla | last post by:
Hi, I want to compare two strings regardless of the lowercase or uppercase. For example, "txt" same as "TXT", "Txt", ... I know that there's stricmp in some c++ that can perform a lowercase comparison. But when I use <cstring>, I can't find such function. Do you know any other standard c++ function(s) can do this task? Thanks,
9
2097
by: collinm | last post by:
hi is there a function who allow to compare string and start at position X example str="print.jpp" ext="jpg" i would like to start to compare str at position 6
19
9516
by: David zhu | last post by:
I've got different result when comparing two strings using "==" and string.Compare(). The two strings seems to have same value "1202002" in the quick watch, and both have the same length 7 which I have tried to print out by debug.writeline(). But the "==" operator results false, and string.Compare() results true. Somebody helps me!
3
1982
by: gerards_ | last post by:
Hi all, What I am trying to do is to String Compare just the first 6 characters of a string. For example: For the compare string "Powama" I want to return true for any strings that contains these first 6 characters (in order).
6
2128
by: Maileen | last post by:
Hi, I have the following code : Function GetRequestType(ByVal EvDt As String, ByVal StPeriod As String, ByVal EdPeriod As String, ByVal TaskType As String) As Integer Dim strtest As String Dim i, j As Integer i = strtest.Compare(EvDt,StPeriod) Select Case (TaskType) Case "Old"
6
1982
by: Gwyn | last post by:
If I test "A+" > "A-" then I get true If I test "A+A" > "A-A" then I get false What the hell is going on?! I can only imagine it's down to culture... but why? my thread culture setting is "en-GB" What rules are going on here? Does this mean the only way I can ever test strings is to use String.CompareOrdinal ??????
4
24882
by: Jim Langston | last post by:
Is there any builtin lowercase std::string compare? Right now I'm doing this: if ( _stricmp( AmmoTypeText.c_str(), "GunBullet" ) == 0 ) AmmoType = Item_Ammo_GunBullet; Is there anything the standard library to do this? I'm not interested in Boost until it becomes part of the standard.
4
3021
by: ndoe | last post by:
how to compare string in file i mean compare that string content digit or alphabet,and 1 question more can we count that line if first line variable = 1,if read second line variable = 2 and so on thanks e.g i have file with name data.txt with file like this 123456
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9333
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3319
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.