问题
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?
回答1:
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.
回答2:
A C++ way to do it would be using std::vector
vector<string> ss;
ss.push_back("a");
ss.push_back("b");
ss.push_back("c");
cout << ss.size(); // number of strings in your vector : 3
you can also access each string :
cout << ss[0].size(); // 1
回答3:
it must be like :
string s[]={"a","b","c"}; //array of string
for(auto i:s){
int len = strlen(i.c_str()); because you need to convert one string to c type string
cout<<len<<" ";
}
to get the array length :
std::array<int> nums {1, 3, 5, 7};
std::cout << "nums contains " << nums.size() << " elements.\n";
http://en.cppreference.com/w/cpp/container/array/size
strlen() accepts ctype strings. and c_str() convert the string(STL) to ctype string(Null terminated) which is accepted by strlen.
回答4:
the define of strlen: size_t strlen ( const char * str ), note the type of input parameter. you define string s[]={"a","b","c"}; which is an array, so the following statement will work: strlen(s[0].c_str()); In addition, to calculate the length of array s, sizeof( s ) / sizeof( s[ 0 ] ) work only when every element of 's' has the same length.
来源:https://stackoverflow.com/questions/14919254/find-the-length-of-string-array-with-strlen