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

C语言程序读取第一个数组后无法输入第二个数组的问题求助

问题:C语言读取数组输入失败,无法处理第二个数组

预期输入格式:

2: [1,-1]
6: [0,1,1,1,1,0]

其中第一个数字代表数组元素个数。但代码读取完第一个数组后直接打印结果,无法进行第二个数组的输入,代码如下:

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

int main() {
    int h, hn, arrH[10]={0}, x, xn, arrX[10]={0};
    scanf("%i: [", &h);   //number of elements of arrH
    for(int i=0; h>0; i++){
        scanf("%i, ", &hn); //scan all elements of array until last one
        if(h==1){
           scanf("%i]\n", &hn); // last one scan with closing brackets
        }
        h--;  
        arrH[i]= hn;
    }
    
    scanf("%i: [", &x); // same process for arrX
    for(int i=0; x>0; i++){
        scanf("%i, ", &xn);
        if(x==1){
           scanf("%i]\n", &xn); 
        }
        x--;  
        arrX[i]= xn;
    }

    for(int i=0; arrH[i]!=0; i++ ){ //printing the 2 arrays
        printf("%i ", arrH[i]);
    }
    
    printf("\n");
    for(int i=0; arrX[i]!=0; i++ ){
        printf("%i ", arrX[i]);
    }
}

错误原因分析

  • scanf格式匹配逻辑错误:处理第一个数组最后一个元素时,代码先执行scanf("%i, ", &hn),但此时输入的最后一个元素后是]而非, ,导致scanf匹配失败,输入缓冲区残留的内容会直接干扰后续第二个数组的读取。
  • 重复读取问题:当h==1时,代码先执行一次普通元素读取,再执行一次带右括号的读取,相当于连续读两次,会错误占用下一行的输入内容,破坏整体输入流程。
  • 数组打印逻辑缺陷:用arrH[i]!=0作为循环终止条件,若数组本身包含0元素(比如第二个数组的首尾0),会提前终止打印,导致输出不完整。

修正后的代码

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

int main() {
    int h, hn, arrH[10] = {0}, x, xn, arrX[10] = {0};
    // 读取第一个数组
    scanf("%d: [", &h);
    for (int i = 0; i < h; i++) {
        // 先读取元素值
        scanf("%d", &hn);
        arrH[i] = hn;
        // 根据位置跳过对应分隔符
        if (i != h - 1) {
            scanf(", "); // 非最后一个元素,跳过逗号和空格
        } else {
            scanf("]"); // 最后一个元素,跳过右括号
        }
    }

    // 读取第二个数组,先跳过换行符避免干扰
    scanf("\n%d: [", &x);
    for (int i = 0; i < x; i++) {
        scanf("%d", &xn);
        arrX[i] = xn;
        if (i != x - 1) {
            scanf(", ");
        } else {
            scanf("]");
        }
    }

    // 用元素个数控制打印循环,避免0元素干扰
    for (int i = 0; i < h; i++) {
        printf("%d ", arrH[i]);
    }
    printf("\n");
    for (int i = 0; i < x; i++) {
        printf("%d ", arrX[i]);
    }

    return 0;
}

修正说明

  1. 调整输入读取逻辑:先读取元素值,再根据是否为最后一个元素跳过对应的分隔符(逗号或右括号),彻底避免格式不匹配问题。
  2. 处理换行符:读取第二个数组前,用scanf("\n%d: [", &x)跳过第一个数组后的换行符,确保第二个数组的元素个数读取正常。
  3. 修改打印逻辑:用数组的实际元素个数作为循环终止条件,不再依赖元素值是否为0,保证输出内容完整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:05:19