c-请检查程序,当我在控制台输入时,它会自动使用换行符



感谢之前的帮助

现在我面临输出问题当我在控制台中输入时,它会自动使用换行符,从屏幕截图中可以明显看出我正在附加

请确定问题

附言:如果有人能告诉我什么是"stdin";我会非常棒 注意:我刚刚更新了代码,请看一下


#include <stdio.h>
#include <string.h>
void input();
void output();
struct book
{
char title[70],id[70],aname[70],price[5];
}b1,b2;
void main()
{
input();
output();
}
void input()
{
int i;
char t[70],in[70],p[5],an[70];
for(i=1;i<3;++i)
{
printf("type the ID for book %d:",i);
fgets(in,70,stdin);
printf("type the title for book %d:",i);
fgets(t,70,stdin);
printf("type the author name for book %d:",i);
fgets(an,70,stdin);
printf("type the price for book %d:",i);
fgets(p,5,stdin);
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.ttIDttTITLEttAUTHOR NAMEttPRICEn");
for(int i=1;i<=2;i++)
{
if(i==1)
{
printf("%dtt%stt%stt%stt%stt",i,b1.id,b1.title,b1.aname,b1.price);
printf("n");
}
if(i==2)
{
printf("%dtt%stt%stt%stt%stt",i,b2.id,b2.title,b2.aname,b2.price);
printf("n");
}

}
}

在此处输入图像描述

您通过不匹配函数声明和函数调用中的参数来调用未定义的行为

您应该从函数定义中删除未传递的和有害的(隐藏全局变量(参数。

此外,您应该在使用函数的点之前添加要使用的函数的标头和声明。

/* add headers */
#include <stdio.h>
#include <string.h>
struct book
{
char title[70],id[70],aname[70],price[5];
}b1,b2,b3;
/* add declarations of functiosn to use */
void input(void);
void output(void);
int main(void) /* use standard signature of main() */
{
input();
output();
return 0;
}
void input(void) /* remove arguments */
{
int i;
char t[70],in[70],p[5],an[70];
for(i=1;i<=3;++i)
{
printf("type the ID for book %d:",i);
gets(in);
printf("type the title for book %d:",i);
gets(t);
printf("type the author name for book %d:",i);
gets(an);
printf("type the price for book %d:",i);
gets(p);
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);
}
else if(i==3)
{
strcpy(b3.id,in);
strcpy(b3.title,t);
strcpy(b3.aname,an);
strcpy(b3.price,p);
}

}
in[i]='';
t[i]='';
an[i]='';
p[i]='';
}
void output(void) /* remove arguments */
{
printf("Sr.No.ttIDttTITLEttAUTHOR NAMEttPRICEn");
for(int i=1;i<=3;i++)
{
if(i==1)
{
printf("%dtt",i);
printf("%stt",b1.id);
printf("%stt",b1.title);
printf("%stt",b1.aname);
printf("%stt",b1.price);
printf("n");
}
if(i==2)
{
printf("%dtt",i);
printf("%stt",b2.id);
printf("%stt",b2.title);
printf("%stt",b2.aname);
printf("%stt",b2.price);
printf("n");
}
if(i==3)
{
printf("%dtt",i);
printf("%stt",b3.id);
printf("%stt",b3.title);
printf("%stt",b3.aname);
printf("%stt",b3.price);
printf("n");
}

}
}

下一步将停止使用gets(),它具有不可避免的缓冲区溢出风险,在C99中已弃用,并从C11中删除。使用fgets()并删除缓冲区中的换行符(具有分隔符"n"strtok()是有用的(将是备选方案。

最新更新