Jump to content

  • Log In with Google      Sign In   
  • Create Account


string comparison problem


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 nuclear123   Members   -  Reputation: 119

Like
0Likes
Like

Posted 18 January 2011 - 10:35 PM

im wanting to compare the sizeof my string with 5 bytes and im curious on how i would do this using c++




for example




char string[5] = "poopy";

how would i check the sizeof this string? and how would i compare it's size(#of bytes) to a specific number of bytes(for example 5) -thx



Sponsor:

#2 Hodgman   Moderators   -  Reputation: 29480

Like
1Likes
Like

Posted 18 January 2011 - 10:45 PM

In C++:
std::string string = "poopy";

if(string.size() == 5)

{

}
In C:
char string[] = "poopy";

if(strlen(string) == 5)

{

}
Note that the C-string "poopy" is 5 characters long, but takes up 6 bytes due to the null-terminator on the end.

#3 Splinter of Chaos   Members   -  Reputation: 239

Like
0Likes
Like

Posted 18 January 2011 - 10:54 PM

C++'s standard sizeof operator will do this.
void f()
{
    char s1[5];
    char* s2;

    cout << sizeof( s1 ) ; // Prints 5
    cout << sizeof( s2 ); // Prints 4 on x86;
}
An array of five chars is also five bytes, so that's why 5 is printed. A pointer to an array is four bytes (on x86 hardware, possibly eight bytes on x64 hardware) so four is printed. Another example is necessary:
void g( char s1[5], char s2[] )
{
    cout << sizeof( s1 ) ; // Prints 5
    cout << sizeof( s2 ); // Prints 4 on x86;
}
If you were using an std::string, you could simply call std::string::size.

#4 rip-off   Moderators   -  Reputation: 8114

Like
0Likes
Like

Posted 19 January 2011 - 05:38 AM

void g( char s1[5], char s2[] )
{
    cout << sizeof( s1 ) ; // Prints 5
    cout << sizeof( s2 ); // Prints 4 on x86;
}

Try it:

#include <iostream>

using namespace std;


void g( char s1[5], char s2[] )
{
    cout << sizeof( s1 ) ; // Prints 5
    cout << sizeof( s2 ); // Prints 4 on x86;
}

int main()
{
   char s1[5];
   char s2[100];
   g(s1, s2);
}
Point here: arrays, when passed to functions, are syntactic sugar for pointers. You can pass an array by reference, but the syntax is a little ugly:

#include <iostream>

using namespace std;


void g( char (&s1)[5], char s2[] )
{
    cout << sizeof( s1 ) ; // Prints 5
    cout << sizeof( s2 ); // Prints 4 on x86;
}

int main()
{
   char s1[5];
   char s2[100];
   g(s1, s2);
}
Doing so preserves the type information (for an array, that includes the size). It also disallows incorrectly sized arrays or pointers being passed, which using an explicit size does not.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS