C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
C++ filling a char array in a loop with user-input: what exactly is happening when a whole string is entered?
我目前正在学习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]
。
由于您的循环只迭代数组p
length
,因此您永远不会越过数组的边界。如果输入的字符多于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.
}
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 用户输入字符串的文件附加问题..C++
- 从 cin 读取不会返回整个输入字符串
- 输出返回编号。等于输入字符串的单词的字符串数
- 控制台未正确读取输入字符串
- 使用终止程序的指针在数组中输入字符串
- 如何删除用户输入字符串末尾的空字符?
- 在循环中使用 cin.get() 输入字符串
- 如何从输入字符串中提取特定位置的字符?
- 用户输入字符串的结构的搜索向量
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 如何在 c++ 中读取输入字符串,忽略空格
- FSTREAM的问题读取确定,但不编写用户输入字符串
- boost::split会在输入字符串不是常量时更改输入字符串吗?
- 通过键盘输入字符串数组和 int 数组的数组大小
- Zlib 放气输入大于原始输入字符串的字符
- C 忽略输入字符串
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词