如何找到字符数组的大小?

Ant*_*ony -1 c++ arrays sizeof char

我应该如何在 C++ 中查找字符数组的长度?我已经尝试了两种方法,但它们都导致数组中的字符数错误。到目前为止,我已经使用了strlensizeof运营商,但无济于事。

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;
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*Cat 5

sizeof(str)是错的。它给你一个指针的大小(str是一个指针),它是一个固定的数字,通常4或者8取决于你的平台。

std::strlen(str)是正确的, 您尝试获取大小之前strtok将一堆插入\0到您的数组中。将停在第一个,并为您提供前面的字符数。strlen\0

调用strlenbeforestrtok并将其返回值保存到变量中。

  • 你是对的 - 但使用 C 风格的字符串/数组无论如何都是不好的。你应该避免这种情况。仅使用以下函数:https://en.cppreference.com/w/cpp/string/basic_string/getline。另外你不应该使用strtok。std::string_view 更快更安全。 (2认同)