c - 为什么在此代码中使用 fgets 时会跳过用户输入?
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char* title;
float price;
} Book;
void Display(Book[], int);
int main()
{
int n;
printf("How many books would you like to create?\n");
scanf("%d", &n);
Book *books = malloc(n * sizeof(*books));
if (books == NULL)
{
printf("ERROR: Out of memory. \n");
return 1;
}
for (int i = 0; i < n; i++)
{
books[i].title = malloc(50);
if (books[i].title == NULL) {
printf("No memory\n");
return 1;
}
printf("Please enter a title for book %d\n", (i+1));
fgets(books[i].title, 50, stdin);
if ((strlen(books[i].title) > 0) && (books[i].title[strlen (books[i].title) - 1] == '\n'))
books[i].title[strlen (books[i].title) - 1] = '\0';
printf("Please enter a price for book %d\n", (i+1));
scanf("%f", &books[i].price);
}
Display(books, n);
for(int i = 0; i < n; i++)
free(books[i].title);
free(books);
return 0;
}
void Display(Book list[], int size)
{
for (int i = 0; i < size; i++)
{
printf("Title: %s, price: %.2f$. \n", list[i].title, list[i].price);
}
}
嘿伙计们,我正在尝试学习 C,但我已经在这个问题上停留了一段时间。我正在尝试制作一个程序,询问用户他想要多少本书,然后继续询问每本书的标题(包括空格)和价格。每当我运行此代码时,结果如下:
How many books would you like to create?
2
Please enter a title for book 1
Please enter a price for book 1
45.4
Please enter a title for book 2
Please enter a price for book 2
245.6
Title: , price: 45.40$.
Title: , price: 245.60$.
为什么标题输入被跳过?
解决方案
你的问题是这个电话:
scanf("%d", &n);
一旦scanf()
完成解析数字,它将未使用的输入留在缓冲区中。因此,用户在数字后键入的换行符就是您的:
fgets(books[i].title, 50, stdin);
作为输入。一个空行。如果您的所有输入都只是fgets()
或只有scanf()
可能有一种干净的方法来处理这个问题。但是,为了让您在开发中取得进展,您可以执行以下操作:
scanf("%d%*c", &n);
scanf("%f%*c", &books[i].price);
哪个会为你吃掉换行符。但是,这不是一个完整的解决方案,因为用户可以在数字后输入一个额外的空格,然后返回,而您又回到了同一条船上。只是一个快速解决方案让您继续前进,然后您可以在对 Google 进行一些研究后返回并正确解决此问题。
推荐阅读
- hive - 在 HDP 3.1.4 中使用 kafka-handler 4.0
- elasticsearch - 弹性搜索(Kibana) - 布尔结果之间的相交
- python - python无法导入嵌套模块
- c# - 多个字段的 C# 不可变计数器
- c - 使用双指针向结构输入值时出现问题
- node.js - AWS Lambda 从 Windows 机器上创建的 zip 文件访问节点模块
- dataweave - 有没有我可以阅读的书可以帮助我使用数据编织?
- python - Python AWS - 从已发送电子邮件中获取RawMessageContent
- xamarin - SkiaSharp 在可点击的路径上制作位图
- c# - UNITY - 玩家控制器不向鼠标光标移动