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

使用scanf_s输入字符时命令控制台出现大量空白间隔的问题

问题原因

你遇到的大量空白间隔是因为输入缓冲区残留的换行符被读取导致的:

  • 用scanf_s("%d", &input)输入整数并按下回车后,回车键对应的\n字符会留在输入缓冲区中。
  • 后续的scanf_s("%c", &inputChar, 1)会直接读取这个\n,而非你手动输入的填充字符。
  • 打印正方形时,程序会把这个\n重复input次,每行输出一个换行,最终表现为大量空白间隔。
解决方案

核心是跳过输入缓冲区中的残留空白字符,推荐两种简单实现方式:

方式1:在scanf_s格式串前加空格

scanf_s的格式串中,空格会自动匹配并跳过所有空白字符(包括换行、空格、制表符)。只需把读取字符的代码改成:

scanf_s(" %c", &inputChar, 1);

注意格式串开头的空格,这是关键。

方式2:手动丢弃换行符

在读取字符前,调用getchar()吃掉缓冲区里的换行:

getchar(); // 丢弃之前输入留下的换行符
scanf_s("%c", &inputChar, 1);
修改后的完整代码

推荐使用第一种方式,修改后的代码如下:

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

void sides(void);

int main(void) {
    sides();
    return 0;
}

void sides(void) {
    int input;
    char inputChar;
    printf("Enter sides of parking lot:  ");
    scanf_s("%d", &input);
    printf("Enter desired character:  ");
    scanf_s(" %c", &inputChar, 1); // 添加空格跳过换行
    int x, y;
    while (input != -1) {
        for (y = 0; y < input; y++) {
            for (x = 0; x < input; x++) {
                printf("%c",inputChar);
            }
            printf("\n");
        }
        printf("Enter sides of parking lot:  ");
        scanf_s("%d", &input);
        printf("Enter desired character:  "); // 移除多余换行,保持提示格式一致
        scanf_s(" %c", &inputChar, 1); // 添加空格跳过换行
    }
}
验证效果

修改后运行,输入流程和输出将与预期一致:

Enter sides of parking lot: 5
Enter desired character: *
*****
*****
*****
*****
*****

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:45:32