Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 字符数组中的元素数_C++ - Fatal编程技术网

C++ 字符数组中的元素数

C++ 字符数组中的元素数,c++,C++,如果我定义了字符数组的大小,但放入的元素较少,如何获得字符数组的大小 #define N 100 char a[N]; cin >> a; 如果我输入126, 那么我该怎么做才能得到这个数组中的elemens 3的数量呢现在你可以使用strlen返回char数组中的字符数。检查我的解决方案 #include <iostream> #include <string.h> #define N 100 using namespace std; int mai

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

#define N 100

char a[N];
cin >> a;
如果我输入126, 那么我该怎么做才能得到这个数组中的elemens 3的数量呢现在你可以使用strlen返回char数组中的字符数。检查我的解决方案

#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。然后代码将如下所示:

包括 包括 int main{ std::字符串a; std::getlinestd::cin,a;
std::cout include和cout为什么将其强制转换为unsigned?printfLength:%zu,strlena;@MariosNikolaou-所以您更喜欢以提供未定义行为的方式打印strlen的结果?@MariosNikolaou-当printf被提供一个类型不同于相应格式说明符的参数时,其行为是未定义的。例如,格式s长无符号的指定符和可能不是长无符号的相应参数。@MariosNikolaou这些文档是错误的。根据标准,strlen函数返回size\u t,这是一个实现定义的无符号类型,而不是有符号整数类型。我想你指的是cin>>a