In C++ I am trying to get size of a string say “gibbs”;
When I am using sizeof function it is returning me size less then one of actual size.
I have below code :
string s = "gibbs";
cout << sizeof(s) <<endl;
and output is : 4. I guess it should be 5.
How to fix this issue. We can add +1 always to return of sizeof but will that be perfect solution ?
sizeof(s)gives you the size of the objects, not the length of the string stored in the objects.You need to write this:
Note that
std::basic_string(and by extensionstd::string) has asize()member function.std::basic_stringalso has alengthmember function which returns same value assize(). So you could write this as well:I personally prefer the
size()member function, because the other containers from the standard library such asstd::vector,std::list,std::map, and so on, havesize()member functions but notlength(). That is,size()is a uniform interface for the standard library container class templates. I don’t need to remember it specifically forstd::string(or any other container class template). The member functionstd::string::length()is a deviation in that sense.