|
发表于 2023-8-25 15:54:40
|
显示全部楼层
这个问题可能是由于编码问题导致的。在使用scanf函数读取字符串时,需要使用"%s"格式化字符串,但是这个格式化字符串只能读取到空格之前的内容,所以如果输入的字符串中包含空格,scanf函数就会停止读取,导致后续的输入被跳过。
解决这个问题的方法是使用fgets函数来读取字符串,它可以读取包含空格在内的整行输入。
下面是修改后的代码:
- #include <stdio.h>
- struct Book
- {
- char title[128];
- char author[40];
- float price;
- unsigned int date;
- char publisher[40];
- };
- int main()
- {
- struct Book book;
- printf("请输入书名:");
- fgets(book.title, sizeof(book.title), stdin);
- printf("请输入作者:");
- fgets(book.author, sizeof(book.author), stdin);
- printf("请输入售价:");
- scanf("%f", &book.price);
- printf("请输入出版日期:");
- scanf("%d", &book.date);
- printf("请输入出版社:");
- getchar(); // 读取之前的换行符
- fgets(book.publisher, sizeof(book.publisher), stdin);
- printf("\n======== 数据录入完毕 ========\n");
- printf("书名:%s\n", book.title);
- printf("作者:%s\n", book.author);
- printf("售价:%.2f\n", book.price);
- printf("日期:%d\n", book.date);
- printf("出版社:%s\n", book.publisher);
- return 0;
- }
复制代码
这样就可以正确读取包含空格的字符串,并输出结构体变量的值了。 |
|