You need to enable JavaScript to run this app. C语言图书管理程序fgets读取stdin时输入自动带换行问题排查
优惠活动
大模型
产品
解决方案
定价
更多

C语言图书管理程序fgets读取stdin时输入自动带换行问题排查

问题解答

1. stdin是什么

stdin是C标准库预设的标准输入流,默认绑定控制台键盘输入,你从键盘敲的所有内容都会先存入stdin的缓冲区,fgets、scanf这类输入函数都是从这个缓冲区里读数据的。

2. 程序读取到多余换行符的原因

你用的fgets函数本身的设计就是会把输入结束时按回车产生的\n字符,一起读到你传入的字符数组里。存到结构体里的字符串末尾自带\n,输出的时候就会自动多换一行,就是你遇到的输出异常。
另外你代码里还有一个隐患:price数组长度只有5,fgets读的时候最多只能存4个有效字符加末尾的\0,输入价格位数稍长就会发生缓冲区溢出,导致未知错误。

3. 修复方案

你可以加一个简单的工具函数,每次用fgets读完内容后,手动删掉字符串末尾的换行符即可,参考修改代码如下:

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

void input();
void output();
// 新增去除换行符的工具函数
void trim_newline(char* str);

struct book
{
  char title[70],id[70],aname[70],price[10]; // price长度改大避免溢出

}b1,b2;

void main()
{
  input();
  output();
}

void trim_newline(char* str) {
    int len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }
}

void input()
{
  int i;
  char t[70],in[70],p[10],an[70]; // p数组对应改长

  for(i=1;i<3;++i)
  {
    printf("type the ID for book %d:",i);
    fgets(in,70,stdin);
    trim_newline(in); // 每次读完去掉换行

    printf("type the title for book %d:",i);
    fgets(t,70,stdin);
    trim_newline(t);

    printf("type the author name for book %d:",i);
    fgets(an,70,stdin);
    trim_newline(an);

    printf("type the price for book %d:",i);
    fgets(p,10,stdin);
    trim_newline(p);

    printf("\n");

    if(i==1)
    {
      strcpy(b1.id,in);
      strcpy(b1.title,t);
      strcpy(b1.aname,an);
      strcpy(b1.price,p);
    }
    else if(i==2)
    {
      strcpy(b2.id,in);
      strcpy(b2.title,t);
      strcpy(b2.aname,an);
      strcpy(b2.price,p);
    }
   
  }

}

void output()
{
  printf("Sr.No.\t\tID\t\tTITLE\t\tAUTHOR NAME\t\tPRICE\n");

  for(int i=1;i<=2;i++)
  {
    if(i==1)
    {
      printf("%d\t\t%s\t\t%s\t\t%s\t\t%s\t\t",i,b1.id,b1.title,b1.aname,b1.price);
      printf("\n");
    }
    if(i==2)
    {
      printf("%d\t\t%s\t\t%s\t\t%s\t\t%s\t\t",i,b2.id,b2.title,b2.aname,b2.price);
      printf("\n");
    }
    
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:45:05