【问题标题】:How to dynamically input array in c++?如何在 C++ 中动态输入数组?
【发布时间】:2019-06-27 08:51:22
【问题描述】:

这是一个简单的代码,我想打印作为输入提供的数组元素。

int main() {
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;

        int *arr = new int[n];
        for(int i=0;i<n;i++)
            cin>>arr[i];

        for(int i=0;i<n;i++)
            cout<<arr[i];
        cout<<endl;
    }
    //code
    return 0;
}

输入:

2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10

此代码产生的输出

123510
2

但这不应该是输出,因为它应该从 1-10 生成另一个数组。

一定有一个愚蠢的错误,但我不知道在哪里

【问题讨论】:

    标签: c++ arrays c++14 dynamic-memory-allocation


    【解决方案1】:

    您的第三行输入缺少 4。

    因此解析为:

    2  // two arrays
    5  // first one size 5
    1 2 3 5
    10  // end of the first array
    1  /* second one size 1 */ 2 /* end of the second array */ 3 4 5 6 7 8 10 
    // the end is ignored
    

    【讨论】:

      【解决方案2】:

      您的代码完美运行!你只是搞砸了你的输入 在第一个示例中,您期望 5 个数字并且只输入 4,而在第二个示例中,您期望 10 个数字并提供 9。 如果您使用 in[5] 创建一个数组,最高索引为 4,但由于索引从 0 开始,因此总大小为 5。 如果这就是你每次都缺少一个元素的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-11
        • 2012-01-02
        • 2017-12-14
        相关资源
        最近更新 更多