Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the length of string array with strlen()

I have been trying to find the length of string which has an array of chars 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 strings 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?

like image 849
DeadCoder Avatar asked Jan 15 '23 05:01

DeadCoder


1 Answers

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.

like image 62
juanchopanza Avatar answered Jan 24 '23 01:01

juanchopanza