Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

c ++ 中设置一个数组输入一串数据当输入-1时停止并输出

  1. User

    c ++ 中设置一个数组输入一串数据当输入-1时停止并输出

  2. Assistant

    以下是一个示例 C++ 代码,实现了在输入一串数据时,当输入-1时停止并输出:

    #include <iostream>
    using namespace std;
    
    int main() {
        int arr[100]; // 声明一个大小为100的整数数组
        int size = 0; // 记录数组的大小
    
        // 输入一串数据,当输入-1时停止
        int num;
        cout << "请输入一串数据,以-1结束:" << endl;
        while (cin >> num && num != -1) {
            arr[size] = num;
            size++;
        }
    
        // 输出数组中的数据
        cout << "输入的数据为:" << endl;
        for (int i = 0; i < size; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    
        return 0;
    }
    

    在该代码中,首先创建了一个大小为100的整数数组 arr,用来存储输入的数据。然后使用一个 while 循环,不断读取用户输入的整数,如果输入的数不是 -1,就将其存入数组中,并将数组大小 size 加一。当输入 -1 时,循环停止。接着使用 for 循环遍历数组,并将数组中的元素输出到控制台上。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.