问题描述
在C ++中,我试图获取字符串的大小
说 gibbs;
In C++ I am trying to get size of a string
say "gibbs";
当我在使用 sizeof
函数返回的尺寸要小于实际尺寸之一。
When I am using sizeof
function it is returning me size less then one of actual size.
我有以下代码:
string s = "gibbs";
cout << sizeof(s) <<endl;
输出为:4.我想应该是5.
and output is : 4. I guess it should be 5.
如何解决此问题。我们可以总是向sizeof返回+1,但这将是完美的解决方案吗?
How to fix this issue. We can add +1 always to return of sizeof but will that be perfect solution ?
推荐答案
sizeof( s)
给出对象 s
的大小,而不是对象 s中存储的字符串的长度
。
sizeof(s)
gives you the size of the object s
, not the length of the string stored in the object s
.
您需要这样写:
cout << s.size() << endl;
请注意 std :: basic_string
(和通过扩展 std :: string
)具有 size()
成员函数。 std :: basic_string
还有一个 length
成员函数,该函数返回与 size()相同的值。
。因此,您也可以这样写:
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;
我个人更喜欢 size()
成员功能,因为标准库中的其他容器,例如 std :: vector
, std :: list
, std :: map
等,具有 size()
成员函数,但没有 length()
。也就是说, size()
是标准库容器类模板的统一接口。我不需要专门针对 std :: string
(或任何其他容器类模板)记住它。成员函数 std :: string :: length()
在这种意义上是一个偏差。
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.
这篇关于C ++中的sizeof显示字符串大小少一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!