【问题标题】:Why in Character Arrays case the `Size() , Length(), strlen()` does not work in C++? [duplicate]为什么在字符数组的情况下,`Size()、Length()、strlen()` 在 C++ 中不起作用? [复制]
【发布时间】:2022-10-05 21:16:59
【问题描述】:

我正在尝试使用在大小为 10 的 char 数组中输入的字符串的长度 c++ 中的 size()、strlen()、length() 函数但它们不起作用,为什么? 但是如果我定义一个字符串 =\"Vishal\" 而不是那个 char 数组,然后使用这些函数,那么它们正在工作为什么会这样???。它在字符串的情况下工作。

#include <bits/stdc++.h>
using namespace std;
int main()
{

    char name[10];
    cin >> name;
    int count = 0;
    for (int i = 0; i < name.size(); i++)
    {
        count++;
    }

    cout << count << \"\\n\";
    return 0;
}
  • namechar[10] 并且没有 size() 成员函数。数组没有成员函数。使用std::strlen(name) 来获得长度 - 或者更好,使用std::string 代替:std::string name; std::getline(std::cin, name); - 然后name.size() 会给你长度。
  • 因为name 是一个非类所以它没有像size 这样的成员。这在任何初学者c++ book 中都有解释。
  • 参考how to ask 第一步是\"搜索然后研究\"你会发现很多相关的 SO 帖子。例如,Array Size Member Function Compile Error
  • 如果您想查找尺寸,请参考How do I find the length of an array?
  • std::string 是一个类类型,它有名为 size 等的成员。所以它们按预期工作。同样,这在任何初学者级别 c++ book 中都有解释。

标签: c++ arrays string string-length strlen


【解决方案1】:

C++ 对数组的使用继承自 C。C 不是面向对象的语言,因此没有方法调用(如 .size())。

出于向后兼容性的原因,C++ 决定从 C 中保留数组,但在新的 C++ 代码中,您几乎应该总是更喜欢 C++ 等效项,例如 std::stringstd::vectorstd::array

【讨论】:

猜你喜欢
  • 2017-09-23
  • 2018-08-28
  • 2019-10-08
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
相关资源
最近更新 更多