求大神指点,为什么这段代码运行后,才输入一个,就显示”请按任意键继续“,不能再输入了
问题描述:
#include<stdio.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char title[128];
char author[40];
char price;
struct Date date;
char publisher;
};
struct Book getinput(struct Book book)
{
printf("书名:");
scanf_s("%s", book.title);
printf("作者:");
scanf_s("%s", book.author);
printf("价格:");
scanf_s("%f", book.price);
printf("出版日期:");
scanf_s("%d-%d-%d", book.date.year,book.date.month,book.date.day);
printf("出版社:");
scanf_s("%s", book.publisher);
return book;
}
void printBook(struct Book book)
{
printf("书名:%s\n", book.title);
printf("作者:%s\n", book.author);
printf("价格:%f\n", book.price);
printf("出版日期:%d-%d-%d\n", book.date.year,book.date.month,book.date.day);
printf("出版社:%s\n", book.publisher);
}
int main()
{
struct Book b1= {"xx","xx",0.0,0-0-0,"xx"},C;
printf("请输入第一本书的信息\n");
C=getinput(b1);
printBook(b1);
return 0;
}
答
scanf_s是要带长度的。
而且非数组类型,scanf_s是要带取地址的。
struct Book
{
char title[128];
char author[40];
float price;
struct Date date;
char publisher;
};
struct Book getinput(struct Book book)
{
printf("书名:");
scanf_s("%s", book.title,20);
printf("作者:");
scanf_s("%s", book.author,20);
printf("价格:");
scanf_s("%f", &book.price);
printf("出版日期:");
scanf_s("%d-%d-%d", &book.date.year, &book.date.month, &book.date.day);
printf("出版社:");
scanf_s("%s", &book.publisher,20);
return book;
}
答
scanf_s("%s", book.title);
改为
scanf_s("%s", book.title,128);
scanf_s函数读入字符串时,需要指定字符串最大长度。后面的scanf_s读入字符串时,全部要这么修改
#include<stdio.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char title[128];
char author[40];
char price;
struct Date date;
char publisher[50];
};
struct Book getinput(struct Book book)
{
printf("书名:");
scanf_s("%s", book.title,128);
printf("作者:");
scanf_s("%s", book.author,40);
printf("价格:");
scanf_s("%f", &book.price);
printf("出版日期:");
scanf_s("%d-%d-%d", &book.date.year,&book.date.month,&book.date.day);
printf("出版社:");
scanf_s("%s", book.publisher,50);
return book;
}
void printBook(struct Book book)
{
printf("书名:%s\n", book.title);
printf("作者:%s\n", book.author);
printf("价格:%f\n", book.price);
printf("出版日期:%d-%d-%d\n", book.date.year,book.date.month,book.date.day);
printf("出版社:%s\n", book.publisher);
}
int main()
{
struct Book b1= {"xx","xx",0.0,0-0-0,"xx"},C;
printf("请输入第一本书的信息\n");
C=getinput(b1);
printBook(b1);
return 0;
}
答
scanf_s("%s", &book.title);
你的输入没有加取地址符号
答
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632