我的数组的长度是多少

What is the length of my array?

本文关键字:多少 数组 我的      更新时间:2023-10-16

大家好,我在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.