获取字符数组C ++的数量

时间:2017-11-04 16:26:41

标签: c++

char array[] {};
cin>>array;

如果我运行此代码,程序会询问用户输入消息,以便用户输入"播放"

array[0] = P
array[1] = l
array[2] = a
array[0] = y

我想创建int变量,其中包含用户输入的字符数 要么 数组的最大索引

谢谢

1 个答案:

答案 0 :(得分:1)

数组在编译时具有固定容量:

char text[1024];

或在运行时动态分配:

cout << "Enter text length: ";
size_t length;
cin >> length;
char *text2 = new char[length];

对于文字,有std::string类型会根据需要进行扩展:

std::string word;
cout << "Enter word: ";
cin >> word;
cout << "Length of word: " << word.length() << "\n";

如果必须使用字符数组,则需要使用str*()系列函数:

char hello[]="hello";
cout << "Length is: " << strlen(hello) << "\n";

首选方法是对文本使用std::string,对数组使用std::vector

警告:请勿使用cin >> character_array,因为cin并不知道阵列的大小,您可能会溢出。
示例:

char word[2];
cin >> word;

现在,输入&#34; world&#34;,数组将溢出。