我应该如何在C++中查找char数组的长度?我已经尝试了两种方法,但它们都导致数组中的字符数错误。到目前为止,我已经使用了strlen
和sizeof
运算符,但都没有用。
void countOccurences(char *str, string word)
{
char *p;
string t = "true";
string f = "false";
vector<string> a;
p = strtok(str, " ");
while (p != NULL)
{
a.push_back(p);
p = strtok(NULL, " ");
}
int c = 0;
for (int i = 0; i < a.size(); i++)
{
if (word == a[i])
{
c++;
}
}
int length = sizeof(str); //This is where I'm having the problem
string result;
cout << length << "n";
if (length % 2 != 0)
{
if (c % 2 == 0)
{
result = "False";
}
else
{
result = "True";
}
}
else
{
if (c % 2 == 0)
{
result = "True";
}
else
{
result = "False";
}
}
if (strlen(str) != 0)
{
cout << result;
}
}
int boolean()
{
char str[1000];
cin.getline(str, sizeof(str));
string word = "not";
countOccurences(str, word);
return 0;
}
sizeof(str)
错误。它为您提供指针的大小(str
是指针(,这是一个固定的数字,通常是4
或8
,具体取决于您的平台。
std::strlen(str)
是正确的,但是strtok
在尝试获取大小之前将一堆