sizeof in c++ showing string size one less

sizeof(s) gives you the size of the object s, not the length of the string stored in the object s.

You need to write this:

cout << s.size() << endl;

Note that std::basic_string (and by extension std::string) has a size() member function. std::basic_string also has a length member function which returns same value as size(). So you could write this as well:

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

I personally prefer the size() member function, because the other containers from the standard library such as std::vector, std::list, std::map, and so on, have size() member functions but not length(). That is, size() is a uniform interface for the standard library container class templates. I don’t need to remember it specifically for std::string (or any other container class template). The member function std::string::length() is a deviation in that sense.

Leave a Comment