I have been trying to find the length of string
which has an array of char
s with strlen()
function but it is not working.
The code I am using is something like this:
string s[]={"a","b","c"};
int len = strlen(s.c_str());
It produces the following error:
"request for member âc_strâ in âwArrayâ, which is of non-class type"
But when I have used this strlen()
function on string
s before like this, it worked fine:
fin.open("input.txt");
string tempStr;
getline(fin, tempStr,'\n');
int len = strlen(tempStr.c_str());
What I am missing here? I know I can find the length of string s[]
with
int size = sizeof( s ) / sizeof( s[ 0 ] );
But why can't I use strlen()
. Can someone explain what is going on?
Finding the length of a fixed size array of any type is easy enough with a helper function template:
#include <cstddef> // for std::size_t
template< class T, size_t N >
std::size_t length(const T (&)[N] )
{
return N;
};
string s[]={"a","b","c"};
std::cout << length(s) << std::endl;
In C++11, the function would be constexpr
.
Concerning strlen, it counts chars
until it finds a null termination character \0
. When you call std::string'sc_str()
method, you get a pointer to the first char
in a null terminated string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With