Length of strings

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.

Why don't you read the documentation for both those functions, to find out what they do?
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 ...
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
Documentation of basic_string::data() and basic_string::c_str() tell about the std::string, particularly that C++98 and C++11 do differ.
std::string is a class and has a "my length" member variable.
tbere is std::string.size(). It works very well and is obvious to use.
Topic archived. No new replies allowed.