If you just want the size of the string, well, use std::string::size()
:
auto size = text.size();
Alternatively, you can use length()
, which does the same thing.
But I'm guessing you're trying to reimplement strlen
for learning purposes. In that case, there are three problems with your code.
First, you're trying to count the number of characters in the string, and that means you need a pointer to char
, not a pointer to std::string
. That pointer should also point to constant characters, because you're not trying to modify those characters.
Second, to get a pointer to the string's characters, use its method c_str()
. Getting the address of the string just gets you a pointer to the string itself, not its contents. Most importantly, the characters pointed to by c_str()
are null terminated, so it is safe to use for your purposes here. Alternatively, use data()
, which has been behaving identically to c_str()
since C++11.
Finally, counting those characters involves checking if the value pointed to by the pointer is '\0'
, so you'll need to dereference it in your loop.
Putting all of this together:
const char* string_ptr = text.c_str(); // get the characters
int size = 0;
while (*string_ptr != '\0') { // make sure you dereference the pointer
size++;
string_ptr++;
}
Of course, this assumes the string does not contain what are known as "embedded nulls", which is when there are '\0'
characters before the end. std::string
can contain such characters and will work correctly. In that case, your function will return a different value from what the string's size()
method would, but there's no way around it.
For that reason, you should really just call size()
.