Get the length (number of chars) of an std::string?

Started by
8 comments, last by deadstar 15 years, 9 months ago
This is driving me nuts!

std::string Test = "hello there everyone";
cout << Test.size() << endl;

or

std::string Test = "hello there everyone";
cout << Test.length() << endl;

Simple code jah? Both return 14...?

"The right, man, in the wrong, place, can make all the dif-fer-rence in the world..." - GMan, Half-Life 2

A blog of my SEGA Megadrive development adventures: http://www.bigevilcorporation.co.uk

Advertisement
STL (the SGI one) documentation says the following about length():
Quote:Synonym for size()
They do the same thing.

My only guess why a string has both is that "length" is a better name and is what other string classes use, whereas "size" is what is used by other STL containers like vectors, lists and sets. Providing size in the string class allows generic container code that calls "size" to work for strings as well.
I think you're missing the point - there are 20 characters in that string, both functions return 14.

Are these the correct functions to get the amount of characters in a string?

"The right, man, in the wrong, place, can make all the dif-fer-rence in the world..." - GMan, Half-Life 2

A blog of my SEGA Megadrive development adventures: http://www.bigevilcorporation.co.uk

Quote:Original post by deadstar
I think you're missing the point - there are 20 characters in that string, both functions return 14.


On my system both return 20. Post your full code program demonstrating the problem.
Maybe std::cout has been set to hex mode previously?
They are the correct functions and both return 20 for me, no 14's in sight.
well i tested out with .size() and .length(), they both showed 20 . so there must be something wrong with your code. maybe assigning some new value to the string somewhere .
you can post your code so we can check it out , ofc if it is not really huge.


best,
y.
Quote:Original post by asp_
Maybe std::cout has been set to hex mode previously?

I'm going to guess the same thing. Try this:
std::string Test = "hello there everyone";std::cout << std::dec << Test.size() << std::endl;

And if that works it's time to start hunting through your code for the stray std::hex modifier that was used but not reset.
Quote:Original post by asp_
Maybe std::cout has been set to hex mode previously?


Yes! That was it! Thank you. I need to watch out for those.

"The right, man, in the wrong, place, can make all the dif-fer-rence in the world..." - GMan, Half-Life 2

A blog of my SEGA Megadrive development adventures: http://www.bigevilcorporation.co.uk

This topic is closed to new replies.

Advertisement