鱼C论坛

 找回密码
 立即注册
查看: 3370|回复: 17

VS code 无法正确输出结构体变量

[复制链接]
发表于 2023-8-25 15:54:40 | 显示全部楼层
这个问题可能是由于编码问题导致的。在使用scanf函数读取字符串时,需要使用"%s"格式化字符串,但是这个格式化字符串只能读取到空格之前的内容,所以如果输入的字符串中包含空格,scanf函数就会停止读取,导致后续的输入被跳过。

解决这个问题的方法是使用fgets函数来读取字符串,它可以读取包含空格在内的整行输入。

下面是修改后的代码:

  1. #include <stdio.h>

  2. struct Book
  3. {
  4.     char title[128];
  5.     char author[40];
  6.     float price;
  7.     unsigned int date;
  8.     char publisher[40];
  9. };

  10. int main()
  11. {
  12.     struct Book book;

  13.     printf("请输入书名:");
  14.     fgets(book.title, sizeof(book.title), stdin);
  15.     printf("请输入作者:");
  16.     fgets(book.author, sizeof(book.author), stdin);
  17.     printf("请输入售价:");
  18.     scanf("%f", &book.price);
  19.     printf("请输入出版日期:");
  20.     scanf("%d", &book.date);
  21.     printf("请输入出版社:");
  22.     getchar(); // 读取之前的换行符
  23.     fgets(book.publisher, sizeof(book.publisher), stdin);

  24.     printf("\n======== 数据录入完毕 ========\n");
  25.     printf("书名:%s\n", book.title);
  26.     printf("作者:%s\n", book.author);
  27.     printf("售价:%.2f\n", book.price);
  28.     printf("日期:%d\n", book.date);
  29.     printf("出版社:%s\n", book.publisher);

  30.     return 0;
  31. }
复制代码


这样就可以正确读取包含空格的字符串,并输出结构体变量的值了。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-22 08:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表