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

C语言最后一个printf无输出排查:带空格符号的字符串无法打印

问题原因及解决方案

问题根源

代码中第三个scanf无法正确读取目标字符串的核心原因是输入缓冲区残留的换行符干扰:

  1. 第一个scanf("%c", &ch)读取输入的C后,输入缓冲区中会留下用户按下的换行符\n。
  2. 第二个scanf("%s", s)会自动跳过开头的空白字符(包括换行符),成功读取Language,但读取完成后,输入缓冲区又会留下Language后的换行符。
  3. 第三个scanf("%[^\n]%*c", sen)的%[^\n]规则是"读取所有非换行符的字符",但此时缓冲区的第一个字符就是换行符,导致匹配失败,sen无法被正确赋值,最终printf输出空内容或乱码。

修复方案

可以通过以下几种方式解决:

方案1:在第三个scanf的格式串前添加空格

空格会自动跳过缓冲区中所有的空白字符(包括换行、空格、制表符等),修改后的代码如下:

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

int main() 
{
    char ch;
    char s[100];
    char sen[100];
    scanf("%c", &ch);
    scanf("%s", s);
    scanf(" %[^\n]%*c", sen); // 格式串前添加空格
    printf("%c\n", ch);
    printf("%s\n", s);
    printf("%s\n", sen);  
    return 0;
}

方案2:在每次scanf后手动清理缓冲区的换行符

在第一个和第二个scanf之后,调用getchar()读取残留的换行符:

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

int main() 
{
    char ch;
    char s[100];
    char sen[100];
    scanf("%c", &ch);
    getchar(); // 清理第一个输入后的换行符
    scanf("%s", s);
    getchar(); // 清理第二个输入后的换行符
    scanf("%[^\n]%*c", sen);
    printf("%c\n", ch);
    printf("%s\n", s);
    printf("%s\n", sen);  
    return 0;
}

方案3:给第一个scanf的格式串前添加空格

同样利用空格跳过空白字符的特性,避免第一个scanf读取到意外的空白,同时配合第三个scanf的空格处理残留换行:

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

int main() 
{
    char ch;
    char s[100];
    char sen[100];
    scanf(" %c", &ch); // 格式串前添加空格
    scanf("%s", s);
    scanf(" %[^\n]%*c", sen);
    printf("%c\n", ch);
    printf("%s\n", s);
    printf("%s\n", sen);  
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:52:51