c++ - cin 采用无效的输入数
问题描述
我将变量分配arrSize
为零 ( int arrSize = 0;
),然后在下一行中,我从用户那里获取变量的输入arrSize
。假设用户分配5 value
给变量。
当我执行我的代码时,Cin
只使用4 values
而不是5
.
但是当我只声明变量( int arrSize; )
而不给它分配任何值时,它工作得很好。
我是新手,能解释一下为什么会这样吗?
谢谢你!
这是我的代码:
#include <iostream>
using namespace std;
int main(){
int arrSize = 0;
int arr[arrSize];
cout << "Enter the array size: ";
cin >> arrSize;
cout << "Enter the elements of the array: ";
for (int i = 0; i < arrSize; i++){
cin >> arr[i];
}
cout << "Output: " << endl;
for (int j = 0; j < arrSize; j++){
cout << arr[j] << endl;
}
}
输出:
解决方案
您的问题是您arr[arrSize]
在阅读之前声明arrSize
。所以你实际上将你的数组声明arr
为arr[0]
.
这种类型的数组称为可变大小或可变长度数组。实际上这是一个非标准特性,如果你想编写跨平台代码,应该避免。至少 GCC 编译器支持此功能。
更好的方法是使数组动态并使用new
关键字对其进行初始化。正如其他答案所提到的,跨平台的编写方式是int* arr = new int[arrSize];
推荐阅读
- javascript - 即使对于反应中的状态 200,API 也没有获取任何响应(Fetch API)
- javascript - 为什么 getExpectedRate() 返回 0?
- ios - 在 Xcode 13 UIButton setBackgroundImage 中不起作用
- go - 如何使用火星代理添加动态标头?
- python - 如何让我的程序知道用户输入的列表是字符串还是数字?
- flutter - 为什么Future返回类型的函数可以返回一个对象而不是Future类型?
- javascript - 在反应中使用 process.env
- click - Javascript AddEventListener 无法识别事件
- javascript - 打开图层:十进制格式的逗号坐标
- html - 当有换行符时,MathJax 2.7.7 无法在网页上正确居中公式