字符数组中的元素数

Number of elements in Char array

本文关键字:元素 数组 字符      更新时间:2023-10-16

如果我定义大小但放置较少的元素,如何获取字符数组的大小

#define N 100
char a[N];
cin >> a;

我输入126, 那么我现在该怎么做才能获得这个数组中的 elemens 数量(在本例中为 3 个(

您可以使用返回字符数组中字符数的strlen()。检查我的解决方案。

#include <iostream>
#include <string.h>
#define N 100
using namespace std;
int main()
{
char a[N];
cout << "Enter number: ";
cin >> a;
cout << "Length: " << strlen(a);
}

由于问题被标记为C++,我首先建议使用std::string而不是char数组。此外,使用std::getline以便使用用户的输入填写声明的std::string。然后代码将如下所示:

#include <iostream>
#include <string>
int main() {
std::string a;
std::getline(std::cin, a);
std::cout << std::endl;
std::cout << "Length: " << a.size() << std::endl;
return 0;
}