When you want to find the size of a std::string, use size():
Code:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s = "Hello, world!";
cout << s.size() << '\n';
}
When you need the size of nul-terminated string (C-style), use strlen():
Code:
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
const char* s = "Hello, world!";
cout << strlen(s) << '\n';
}
You get unexpected results in your code, because you misunderstand what sizeof does. It gives the size of an object (or pointer) in bytes, not the length of a string. For example, if int is 32 bit and a byte is 8 bits on a particular machine, then sizeof(int) == 4.
On many systems a pointer is 4 bytes. std::string is often implemented like this:
Code:
// It is actually template<typename E, typename CharT = char_traits<E> > class basic_string
// but do not worry about that right now
class string
{
struct Data
{
char* end;
char* endOfMem;
char buf[1];
};
Data* data_;
public:
// public implementation...
};
This means that a string object contains exactly one pointer, which makes its size 4. That is why in your example, sizeof s == 4.
The only place where sizeof can return the length of a nul-terminated string is when it is an array:
Code:
#include <iostream>
using namespace std;
int main()
{
char s[] = "Hello, world!";
cout << sizeof s - 1 << '\n';
}
In this case, s is an array of chars, so sizeof knows the actual size of the array. However, you will get one character more, since sizeof counts the terminating '\0' as well, so you just subtract one and get the correct result.
In conclusion, when you need the length of a std::string use its size() member function and when you need the length of a nul-terminated string use strlen. Furthermore, invest in some good books because these are the basics and you should understand them well.