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

如何修复输入非数字字符导致的scanf无限循环问题

解决C语言矩阵程序中输入非数字字符的异常问题

问题1:矩阵大小输入的无限循环修复

原代码中,输入非数字字符时scanf("%d", &n)会读取失败,返回0,且错误字符会留在输入缓冲区,导致后续循环反复读取无效字符,陷入无限循环。修复代码如下:

int n;
do {
    printf("Define the size of the matrix: ");
    // 捕获scanf返回值,成功读取整数则返回1
    int input_ret = scanf("%d", &n);
    if (input_ret != 1) {
        // 清空输入缓冲区中所有残留的无效字符
        while (getchar() != '\n');
        // 将n设为无效值,确保循环继续执行
        n = 0;
    }
} while (n <= 1);

修复逻辑

  • 检查scanf返回值:若返回值不等于1,说明输入不是有效整数。
  • 用while(getchar() != '\n')清空输入缓冲区,避免无效字符干扰后续输入。
  • 将n重置为0(满足n <=1),让循环继续要求用户输入。

问题2:矩阵元素输入的异常修复

输入非数字字符时scanf("%lf", ...)会读取失败,残留字符会导致后续输入异常。修复后的函数会在输入无效时提示错误,并重试当前元素的输入:

void input_matrix(double* matrix, int n) {
    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < n; j++) 
        {
            int input_ret;
            do {
                // 修正原代码行列顺序错误:行号为i+1,列号为j+1
                printf("Define the value of %d. row a %d. column:\t", i+1, j+1);
                input_ret = scanf("%lf", &matrix[i*n+j]);
                if (input_ret != 1) {
                    // 清空缓冲区的无效字符
                    while (getchar() != '\n');
                    printf("Invalid input, please enter a number.\n");
                }
            } while (input_ret != 1); // 直到输入有效数字才进入下一个元素
        }
    }
}

修复逻辑

  • 给每个元素的输入套do-while循环,确保只有输入有效数字时才退出。
  • 输入无效时清空缓冲区,同时提示用户重新输入。
  • 修正了原代码中行列号显示颠倒的问题。

内容的提问来源于stack exchange,提问作者Samuel Gombárik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:13:13