Jump to content
  • Advertisement
Sign in to follow this  
deadstar

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

This topic is 3631 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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...?

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!