Page 1 of 1

C++ another n00b question (strlen() for "string" t

Posted: Sat Mar 25, 2006 1:38 pm
by Chris Corbyn
How do you work work out the length of a "string" in C++?

For char* it's easy:

Code: Select all

char *foo;

int main()
{
    foo = strdup("foobar");
    cout << strlen(foo) << endl;
    return 0;
}
But with a "string" type (which from what I've read is a better way to go since it's available in C++) you get a conversion error with that :(

sizeof() just returns 4 bytes all the time. I'm sure it's something stupidly simple but I can't find it on Google and my text book doesn't seem to mention much about "string" types.

Posted: Sat Mar 25, 2006 2:08 pm
by Chris Corbyn
/Hangs head in shame :oops:

Code: Select all

string foo = "foobar";

/** snip **/

cout << foo.length() << endl;

Posted: Sat Mar 25, 2006 4:33 pm
by timvw
No worries, i've always found C/C++ and all the string approaches quite confusing ;)

char *, std::string, TCHAR, BSTR, ... ;)

Posted: Sat Mar 25, 2006 4:41 pm
by feyd
ahh, my friend typedef, how I miss thee. :)

Posted: Sat Mar 25, 2006 4:46 pm
by Chris Corbyn
timvw wrote:No worries, i've always found C/C++ and all the string approaches quite confusing ;)

char *, std::string, TCHAR, BSTR, ... ;)
Yeah there sure are a heck of a lot of different ways of handling strings. It's probably easier to write your own string class and just use that wherever you work with strings :idea:

Posted: Sun Mar 26, 2006 2:32 am
by timvw
Now that i come to think of it, it was still very amusing when i wrote my last C++ application ;)

Eg: Some C++.NET managed/unmanaged code

Code: Select all

String ^type = "some type";
stl::string ttype = new string((char*) Marshal::StringToHGlobalAnsi(type).ToPointer());

Posted: Fri Mar 31, 2006 12:26 am
by alex.barylski
d11wtq wrote:
timvw wrote:No worries, i've always found C/C++ and all the string approaches quite confusing ;)

char *, std::string, TCHAR, BSTR, ... ;)
Yeah there sure are a heck of a lot of different ways of handling strings. It's probably easier to write your own string class and just use that wherever you work with strings :idea:
:lol:

Stick with STL... :)

It's portable across multiple platforms, well tested and efficient as it's gonna get for what it does for you.

STL, because it's implemented using templates not classes (per se), the syntax is a little wonky at first and the addition of iterators complicate things but in the long run you'll grow to really appreciate such a useful library of data structures & container classes.

Cheers :)