我的数组的长度是多少
What is the length of my array?
大家好,我在strlen和数组方面遇到了问题,它一直说我的字符串长度只有一?如果有人能帮忙,那就太好了,这是我的代码:
#include <iostream>
using namespace std;
#include <cstring>
int main()
{
char word1[20];
int len = strlen(word1);
cout << "enter a word!n";
cin.get(word1, 20, 'n'); cin.ignore(50,'n');
cout << len;
}
只需阅读评论中的内容,更新我的答案,尝试在发生的事情背后提供更多直觉。
char word1[20];
在计算机内存中设置一个位置,该位置最终可以由最多20个字符的数据填充。请注意,仅凭这句话并不能"清除"目前存在的任何东西的记忆。正如sfjac所指出的,这意味着任何东西都可能在那个空间里。这个空间中的任何东西都不太可能是一个字符或任何你的代码可以轻易理解的东西。
int len = strlen(word1);
创建一个整数,并将其设置为等于word1
中当前字符数的值。请注意,因为我们没有为word1
指定任何内容,所以您正在获取该内存空间中发生的任何内容的长度。您已将最大值限制为20,但在这种情况下,无论其中有什么数据垃圾,都会给您1的长度。
cout << "enter a word!n";
提示用户输入单词
cin.get(word1, 20, 'n'); cin.ignore(50,'n');
获取单词,将其存储在word1
中。在这一点上,word1
现在被定义为具有实际内容。但是,您已经定义了变量len
。计算机不知道如何自动为您重新定义。它按顺序遵循您提供的步骤。
cout << len;
打印存储在len
中的值。因为len
是在用户输入数据之前创建的,所以len
与用户输入的内容完全无关。
希望这能给你一些直觉,帮助你超越这个问题!
@Chris是正确的,但可能只是一个小小的解释。当您在堆栈上声明像char word1[20]
这样的字符数组时,该数组将不会初始化。strlen
函数通过计算从word1
地址到内存中第一个空字节的字符数来计算数组的长度,这几乎可以是任何字符。
我强烈建议对文本使用std::string
。
如果必须使用字符数组:
- 为容量定义一个命名标识符
- 使用命名标识符定义数组
- 容量应考虑到终止nul,"\0",字符到标记最大文本长度的末尾
使用上述指南,您就有了简单的程序:
int main(void)
{
std::string a_word_string;
std::string line_of_text_string;
const unsigned int c_string_capacity = 32U;
char c_string[c_string_capacity];
// The std::string functions
cout << "Enter some text: ";
getline(cin, line_of_text_string); // read a line of text
cout << "nEnter a sentence: ";
cin >> a_word_string;
cin.ignore(10000, 'n'); // Ignore remaining text in the buffer.
// The C-style string functions
cout << "Enter more text: ";
cin.read(c_string, c_string_capacity);
c_string[c_string_capacity - 1] = ' '; // Insurance, force end of string character
cout << "You entered " << (strlen(c_string)) << " characters.n";
return EXIT_SUCCESS;
}
std::string
类效率更高,可以动态处理大小变化。
数组的长度是定义数组时使用的c_string_capacity
的值。
数组中文本的长度定义为strlen(c_string)
,这是在找到终止nul之前的字符数。
您必须在读取word1
之后计算len
,否则将留下未定义的行为
char word1[20];
cout << "enter a word!n";
cin.get(word1, 20, 'n'); cin.ignore(50,'n');
int len = strlen(word1);
cout << len;
在声明对象时总是初始化对象是个好主意。由于作用域内的对象不能保证被初始化
例如,在C++11中,您可以执行以下操作:
char arr[10]{}; // this will initialize the objects in the array to default.
char arr[10]{0}; // the same.
- C++,数组有多少个地址?
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 在 C++ AMP 数组中复制数据多少次?
- C++ 检查结果数组中有多少次数字
- 将数组的元素插入映射的时间复杂度是多少?
- 当我们不使用空字符显式初始化字符数组时,字符串的长度是多少?
- 我怎么知道数组包含多少个元素C++?
- 数组由其类自己的指针指向的大小是多少?
- c++ 中堆上数组的默认值是多少?
- 如何知道我想在数组中存储多少索引
- 我们可以在 C++ 编程中使用的二维数组的最大大小是多少?
- 指针数组中将有多少内存分配
- C++如何打印在2数组中重复多少个元素
- 找出数组中有多少不同的浮点值
- 在计算使用了多少个数组索引的同时,如何填充一个来自用户输入的字符的数组?(使用cin.get)
- 如果我自己不分配数组元素,数组元素的值是多少
- 遍历二维数组的时间复杂度是多少
- 我的数组的长度是多少