You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何处理输入元素数量小于数组大小的情况?

解决数组输入元素不足时程序阻塞的问题

当原代码用scanf强制循环读取10个整数时,用户必须输入满10个值程序才会继续,以下几种方法可以让程序接受少于设定大小的输入:

方法1:检查scanf的返回值

scanf会返回成功读取的变量个数,当输入无法匹配整数(比如输入字母、符号),或者用户按下输入结束快捷键(Unix/Linux按Ctrl+D,Windows按Ctrl+Z)时,返回值不等于1,此时可终止循环。

修改后的代码:

#include <iostream>
using namespace std;

const int SIZE = 10;
int arr[SIZE] = {};

int main() {
    cout << "Size of the array is " << SIZE << "\n";
    cout << "Input values (Separate values by space, enter non-number to end): ";

    for(int i = 0; i < SIZE; i++) {
        // 检查是否成功读取整数
        if(scanf("%d", &arr[i]) != 1) {
            break;
        }
    }
    return 0;
}

方法2:读取整行输入再分割

先读取用户输入的整行内容,再从中提取所有整数,处理完后直接停止,剩余数组元素保持初始的0值。需要引入<sstream>头文件:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

const int SIZE = 10;
int arr[SIZE] = {};

int main() {
    cout << "Size of the array is " << SIZE << "\n";
    cout << "Input values (Separate values by space): ";
    
    string line;
    getline(cin, line); // 读取整行输入
    istringstream iss(line);
    
    int count = 0;
    while(iss >> arr[count] && count < SIZE) {
        count++;
    }
    
    cout << "You entered " << count << " valid integer(s)\n";
    return 0;
}

这种方式更友好,用户输入完所有想输入的值后直接回车即可,无需额外输入终止符。

方法3:用cin替代scanf

cin在输入失败时会触发失败状态,利用这一特性可以简洁地终止循环:

#include <iostream>
using namespace std;

const int SIZE = 10;
int arr[SIZE] = {};

int main() {
    cout << "Size of the array is " << SIZE << "\n";
    cout << "Input values (Separate values by space): ";

    int i = 0;
    while(i < SIZE && cin >> arr[i]) {
        i++;
    }
    return 0;
}

当输入非整数或用户结束输入时,cin >> arr[i]会返回false,循环自动停止。

内容的提问来源于stack exchange,提问作者GrumpyBambino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:25:46