【发布时间】: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;
}
-
name是char[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