s.length() against s[0] = '\0'

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
trulo17
Learning poster
Posts: 62
Joined: Mon Jan 24, 2005 6:12 am
Location: Lima,Peru

s.length() against s[0] = '\0'

Post by trulo17 » Fri Sep 02, 2005 10:33 pm

i thought these two statements are the same

if( A[0] == '\0' || B[0] == '\0' )

if( A.length() == 0 || B.length() == 0 )

where A and B are c++ strings

but they aren't, since i got Acc( problem 10100 ) with the second one, but a WA with the first one( that's the only thing i changed ) Could somebody give an explanation?

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Fri Sep 02, 2005 11:20 pm

C-style strings are '\0'-ended. std::strings are not.

misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Post by misof » Fri Sep 02, 2005 11:21 pm

C++ strings do not guarantee anything when using [] to index outside of the interval [ 0, size() ). Specially, the next char in memory after the place where the current contents of the string is stored doesn't have to be zero. C++ strings have a method c_str() that returns a pointer to a null-terminated version of the string.

E.g.

Code: Select all

string s = "hello";
printf("%s\n",s.c_str());

Post Reply

Return to “C++”