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

C语言二维数组存储输入单词后无法完整打印问题求助

问题分析与解决

我尝试获取用户输入并保存出现的单词,思路是先将字母存入数组组成单词,再将每个单词存入二维数组中。但目前仅能打印出第二个单词的内容,第一个单词的内容被忽略了。我是C语言初学者,若有低级失误请见谅。

我的代码

#include <stdio.h>

#define NEW_LINE 10
#define TAB 9
#define SPACE 32

int main() {
    int c;
    int counter1 = 0;
    int counter2 = 0;
    int word[10][10] = { { 0 } };

    while ((c = getchar()) != EOF) {
        if (c != TAB && c != NEW_LINE && c != SPACE) {
            word[counter1][counter2] = c;
            ++counter2;
        } else {
            counter2 = 0;
            ++counter1;
        }
    }

    for (int a = 0; a <= 9; ++a) {
        printf("
");
        for (int b = 0; b <= 9; ++b) {
            printf("%4d", word[a][b]);
        }
    }

    return 0;
}

程序输出

输入Hello World后,输出如下:

Hello World

  87 111 114 108 100   0   0   0

(输出截图显示内容与上述文本输出一致)


问题原因与修复方案

1. 核心错误:换行符书写错误

打印循环里的printf(" ");是语法错误,C语言中换行符必须写成\n。这个错误直接导致输出混乱,第一个单词的内容被覆盖或无法正确换行显示,这是你看不到第一个单词的主要原因。

2. 连续分隔符导致数组行浪费

遇到连续的空格、换行或制表符时,代码会多次执行++counter1,二维数组的行被空占,后续单词会存在更靠后的行里,甚至可能超出数组范围引发未定义行为。

修复后的代码

#include <stdio.h>

#define NEW_LINE 10
#define TAB 9
#define SPACE 32

int main() {
    int c;
    int counter1 = 0;
    int counter2 = 0;
    int word[10][10] = { { 0 } };

    while ((c = getchar()) != EOF) {
        if (c != TAB && c != NEW_LINE && c != SPACE) {
            // 限制单词长度不超过数组列上限
            if (counter2 < 9) {
                word[counter1][counter2] = c;
                ++counter2;
            }
        } else {
            // 仅当当前正在记录单词时,才切换到下一行
            if (counter2 > 0) {
                counter2 = 0;
                // 限制行索引不超过数组行上限
                if (counter1 < 9) {
                    ++counter1;
                }
            }
        }
    }

    // 仅打印实际存储了单词的行
    for (int a = 0; a <= counter1; ++a) {
        printf("\n");
        for (int b = 0; b < 10; ++b) {
            // 遇到单词末尾的0时提前终止,输出更整洁
            if (word[a][b] == 0 && b > 0) {
                break;
            }
            printf("%4d", word[a][b]);
        }
    }

    return 0;
}

修复说明

  • 修正换行符写法,用printf("\n");实现正确换行;
  • 添加数组边界检查,避免索引超出数组范围,防止未定义行为;
  • 优化分隔符处理逻辑,仅在结束一个单词后才切换到下一行,避免空行占用数组空间;
  • 打印时只遍历到实际存储的最后一行,遇到单词末尾的0提前终止打印,输出更简洁。

测试效果

输入Hello World后,输出会变成:

72 101 108 108 111
  87 111 114 108 100

(分别对应Hello和World的ASCII码)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:58:30