在C++语言中,可以使用以下代码实现数组输入遇到回车时退出输入:

#include <iostream>
using namespace std;

int main() {
    const int MAX_SIZE = 100;
    int arr[MAX_SIZE];
    int size = 0;
    int num;

    while (size < MAX_SIZE && cin >> num) {
        arr[size] = num;
        size++;
        if (cin.get() == '\n') {
            break;
        }
    }

    cout << "Array elements: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

在上述代码中,使用cin读取用户输入的数字,并将其存储在数组arr中。在每次读取数字后,使用cin.get()方法读取下一个字符,如果读取到的字符是回车符\n,则退出输入循环。最后,输出数组中的元素。

注意,为了避免数组越界,需要定义一个数组的最大长度MAX_SIZE。如果用户输入的数字个数超过了MAX_SIZE,则只会存储前MAX_SIZE个数字。

数组输入遇到回车时退出输入C加加语法

原文地址: https://www.cveoy.top/t/topic/0sr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录