How to input an array in C++?

In C++, loops and input stream objects can be used to input arrays.

Here is a common method:

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "请输入数组的大小:";
    cin >> n;

    int arr[n];
    cout << "请输入" << n << "个整数:";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    cout << "您输入的数组为:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

The code above first asks the user to input the size of an array, then creates an integer array of the specified size. Next, it uses a loop structure to sequentially receive user input integers and store them in the array. Finally, it outputs the elements in the array.

Please note that this method is only applicable for C++11 and higher versions. For C++03 and earlier versions, creating dynamic arrays requires using the “new” operator.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds