使用strlen()查找字符串数组的长度, [英] Find the length of string array with strlen()
问题描述
我一直在尝试找到 string
的长度 char
$ c> strlen()函数,但它不工作。
我使用的代码是这样的:
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());
会产生以下错误:
"request for member âc_strâ in âwArrayâ, which is of non-class type"
但是当我在 string
s上使用这个 strlen()
:
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());
我在这里缺少什么?我知道我可以找到 string s []
的长度
What I am missing here? I know I can find the length of string s[]
with
int size = sizeof( s ) / sizeof( s[ 0 ] );
但是为什么我不能使用 strlen()
。
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;
在C ++ 11中,函数 constexpr
。
In C++11, the function would be constexpr
.
关于 strlen ,它计数 chars
,直到它找到一个空终止字符 \0
。当您调用 std :: string 的 c_str( )
方法,您将在一个空终止字符串中获得指向第一个 char
的指针。
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.
这篇关于使用strlen()查找字符串数组的长度,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!