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

C语言代码执行输出前出现多余换行符该如何消除

问题修复方案

核心问题定位

输出前多空行是数组越界访问导致:
你定义的temp_word_1、temp_word_2两个二维数组长度为nbr_words,合法下标范围是0 ~ nbr_words-1。但你写的输出循环判断条件为nbr_words >= 0,第一次执行时会直接访问下标为nbr_words的非法内存空间,该空间存储的不确定值恰好为空,因此会先打印一行空内容加换行,就是你看到的首行空行。

额外可优化点

你的scanf格式串里存在多余的空白符:

  • scanf("%d\n", &nbr_words)里的\n
  • scanf("%s ", word_1)里的后缀空格
    %d、%s这类格式符本身会自动跳过输入前的所有空白字符(空格、换行、制表符),多余的空白符会让scanf持续吞掉所有连续空白,直到遇到非空白字符才停止,可能导致特殊输入场景下的行为异常。

修复后完整代码

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

int main(void)
{
    int nbr_words;
    char word_1[51];
    char word_2[51];
    int i;

    // 去掉格式串多余的\n
    scanf("%d", &nbr_words);

    char temp_word_1[nbr_words][51];
    char temp_word_2[nbr_words][51];

    i = 0;
    while (i < nbr_words)
    {
        // 去掉格式串多余的后缀空格
        scanf("%s", word_1);
        strcpy(temp_word_1[i], word_1);
        scanf("%s", word_2);
        strcpy(temp_word_2[i], word_2);
        i++;
    }

    // 修正循环边界,从最后一个合法下标开始输出
    while (--nbr_words >= 0)
    {
        printf("%s %s\n", temp_word_2[nbr_words], temp_word_1[nbr_words]);
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:09:04