C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?

C++ filling a char array in a loop with user-input: what exactly is happening when a whole string is entered?

本文关键字:输入 字符串 发生了 什么 数组 用户 循环 C++ char 填充      更新时间:2023-10-16

我目前正在学习C++,我想我错过了一些基本的东西。我很难理解这里到底发生了什么:

#include <iostream>
int main(){
int length = 0;
std::cin >> length;
char p[length];
int i = 0;
while(i < length){
std::cin >> p[i];
std::cout << ++i;
}
std::cout << p;
}

如果我输入5作为字符数组长度,然后输入整个字符串abcdef我会得到12345abcde.

我想知道为什么字符串首先是可接受的输入,以及为什么它仍然贯穿循环的其余部分并每次递增i。 我会假设字符串被保存到数组中(为什么字符串比数组长并且不会出现错误?)然后预期会有更多的输入 - 然后会被忽略(?),因为数组已满。或者我会期望像Java那样的OOB。

你错过了很多基础知识:

std::cin >> length;
char p[length];

数组的大小必须在编译时知道(长度必须是编译时常量表达式)。显示的代码在C++格式不正确。

我想知道为什么字符串首先是可以接受的输入

标准输入是字符流。字符串是它非常自然的输入。

以及为什么它仍然贯穿循环的其余部分并每次递增 i。

重复循环,直到条件为真。增量没有条件,因此在每次迭代中都会重复。最终i将达到最终条件。

我会假设字符串已保存到数组中

至少其中一些是。

为什么字符串比数组长是可以的...?

这不行。我认为没有理由假设它是。

并且不会出现错误

未指定在越界访问数组时引发错误的语言。相反。。。

然后将被忽略 (?),因为数组已满。

行为未定义。

或者我会期望像Java那样的OOB。

我建议不要基于其他语言做出假设。

cin >> p[i]正在做的是在命令行上查找字符。 此调用将阻止,直到找到字符。找到字符时,循环将迭代,接受字符进入p[i]

由于您的循环只迭代数组plength,因此您永远不会越过数组的边界。如果输入的字符多于length中指定的字符,则这些字符仅保留在输入缓冲区中。

更好的解决方案是在char数组上使用std::string

">

我很难理解这里到底发生了什么:">

我已经在您的代码中添加了注释来解决上面的问题。

#include <iostream>
int main(){
int length = 0;             // declare an integer variable length and set it to 0
std::cin >> length;         // get input from user and store it in variable length
char p[length];             // declare a character array named p to the size of "length"
// this is not legal in standard c++. It is an extension 
// that some compilers support as pointed out by (drescherjm)
int i = 0;                  // declare an integer variable i and set it to 0
while(i < length){          // loop block while i is less then the value of length
std::cin >> p[i];         // get input from user and store that value in element i of the p array
std::cout << ++i;         // increment the value of i and output the value to the console
}
std::cout << p;             // output the the contents of the p array to the console.
}