首页 > 解决方案 > 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;
    }


}

输出:

标签: c++arrayscin

解决方案


您的问题是您arr[arrSize]在阅读之前声明arrSize。所以你实际上将你的数组声明arrarr[0].

这种类型的数组称为可变大小或可变长度数组。实际上这是一个非标准特性,如果你想编写跨平台代码,应该避免。至少 GCC 编译器支持此功能。

更好的方法是使数组动态并使用new关键字对其进行初始化。正如其他答案所提到的,跨平台的编写方式是int* arr = new int[arrSize];


推荐阅读