Aug 16, 2013 at 10:14am UTC
I need to know when I call std::string::length() and strlen(char*) on "hi" and they both output 2 does that start at 0 and really mean 3 because the null terminated character at the end.
Aug 16, 2013 at 10:22am UTC
Why don't you read the documentation for both those functions, to find out what they do?
Aug 16, 2013 at 10:34am UTC
Dude I did... That's why I'm of course asking. Plus I'm only on my iPhone so it's hard to look at documentation ...
Aug 16, 2013 at 10:45am UTC
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <cstring>
int main()
{
const size_t N = 10;
char s[N] = "hi" ;
std::cout << "sizeof( s ) = " << sizeof ( s )
<< ", strlen( s ) = " << std::strlen( s ) << std::endl;
}
The output will be
sizeof( s ) = 10, strlen( s ) = 2
Function std::strlen counts characters until the zero-terminating character will be encountered.
So though character array s has 10 characters and contains three actual characters including the terminating zero function strlen will return 2.
Last edited on Aug 16, 2013 at 10:47am UTC
Aug 16, 2013 at 11:11am UTC
Documentation of basic_string::data()
and basic_string::c_str()
tell about the std::string, particularly that C++98 and C++11 do differ.
Aug 16, 2013 at 11:36am UTC
std::string is a class and has a "my length" member variable.
Aug 16, 2013 at 4:28pm UTC
tbere is std::string.size(). It works very well and is obvious to use.