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

输入整数序列后按空格加回车,getchar()仍等待输入如何解决

问题:处理带末尾空格的整数输入序列

需求是读取空格分隔的整数序列到数组中,当前代码在输入数字后直接按回车时运行正常,但如果输入数字后先按空格再按回车,程序会换行等待更多输入,需要解决这个问题。

原代码如下:

#include <stdio.h>
#include <stdbool.h>

#define MAX_VALUES 250000

int main() 
{
    int sequence[MAX_VALUES];
    int count = 0;
    do {
        scanf("%d", &sequence[count++]);
    }
    while(getchar() != '\n');

    for(int i = 0; i < count; i++) {
        printf("Element is: %d\n", sequence[i]);
    }

    return 0;
}

问题原因

当前循环逻辑是读取一个整数后,用getchar()判断下一个字符是否是换行。如果输入末尾有空格,getchar()会先读到这个空格而非换行符,循环会继续执行,此时scanf会等待输入下一个整数,导致程序卡住。

另外原代码还有两个隐患:

  • 未判断count是否超过MAX_VALUES,可能导致数组越界
  • 未检查scanf的返回值,如果输入非整数,会触发无限循环

解决方案

方案1:修改原循环逻辑,跳过空白字符

在读取整数后,先跳过所有空白字符(空格、制表符等),直到遇到换行符或非空白字符,若遇到换行则终止循环。同时增加数组边界和scanf返回值判断:

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h> // 用于isspace函数

#define MAX_VALUES 250000

int main() 
{
    int sequence[MAX_VALUES];
    int count = 0;
    int ch;
    int scan_result;

    do {
        scan_result = scanf("%d", &sequence[count]);
        // 如果读取失败(非整数输入)或数组已满,终止循环
        if (scan_result != 1 || count >= MAX_VALUES - 1) {
            break;
        }
        count++;

        // 跳过所有空白字符
        while ((ch = getchar()) != '\n' && isspace(ch));
        // 遇到换行符就退出循环
        if (ch == '\n') {
            break;
        }
    } while (true);

    for(int i = 0; i < count; i++) {
        printf("Element is: %d\n", sequence[i]);
    }

    return 0;
}

方案2:先读取整行再解析(更鲁棒)

用fgets读取整行输入,再通过strtok分割字符串提取整数,这种方式不受末尾空格影响,同时避免scanf的阻塞问题:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_VALUES 250000
#define MAX_LINE_SIZE 1048576 // 定义足够大的行缓冲区

int main() 
{
    int sequence[MAX_VALUES];
    int count = 0;
    char line[MAX_LINE_SIZE];
    
    // 读取整行输入,失败则直接退出
    if (fgets(line, sizeof(line), stdin) == NULL) {
        return 1;
    }

    // 按空白字符分割字符串,提取整数
    char *token = strtok(line, " \n\t");
    while (token != NULL && count < MAX_VALUES) {
        sequence[count++] = atoi(token);
        token = strtok(NULL, " \n\t");
    }

    for(int i = 0; i < count; i++) {
        printf("Element is: %d\n", sequence[i]);
    }

    return 0;
}

方案对比

  • 方案1基于原代码修改,改动较小,适合快速修复问题
  • 方案2逻辑更清晰,能处理整行输入,避免scanf的各种边界问题,推荐用于生产环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:32:40