c - 当结构指针传递给函数时,为什么 fgets 在我的代码中不起作用?
问题描述
这是简单的代码,当我们从结构 book 创建一个指针 book1 然后我们为其分配内存但是当这个指针 book1 被传递给函数 get_info 并且当 fgets 应该从用户那里获取值时,它只是跳过它而不使用 fgets 获取值但与 %s 完美配合。
#include <stdio.h>
#include <stdlib.h>
struct book{
char title[100];
char author[100];
};
void get_info (struct book *b1){
printf("Enter the author: ");
fgets(b1->author, sizeof(b1->author) , stdin);
printf("Enter the title: ");
scanf("%s",b1->title);
}
void display_book (struct book *b1){
printf("Title: %s\n", b1->title);
printf("Author: %s\n",b1->author);
}
int main(){
struct book *book1;
int n;
printf("Enter number of book to enter: ");
scanf("%d",&n);
book1=(struct book*)malloc(n*sizeof(struct book));
for (int i=0; i<n; i++){
get_info(book1+i);
display_book(book1+i);
}
return 0;
}
解决方案
您的代码有几个问题。你混合scanf
,fgets
然后你忘记了它fgets
的结束。
我修好了它:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book {
char title[100];
char author[100];
};
void get_info(struct book* b1) {
printf("Enter the author: ");
fgets(b1->author, sizeof(b1->author), stdin);
b1->author[strcspn(b1->author, "\r\n")] = 0; // remove trailing newline
printf("Enter the title: ");
fgets(b1->title, sizeof(b1->title), stdin);
b1->title[strcspn(b1->title, "\r\n")] = 0; // remove trailing newline
}
void display_book(struct book* b1) {
printf("Title: %s\n", b1->title);
printf("Author: %s\n", b1->author);
}
int main() {
struct book* book1;
char buf[10];
int n;
printf("Enter number of book to enter: ");
fgets(buf, sizeof(buf), stdin);
if (sscanf(buf, "%d", &n) != 1) {
printf("Invalid value entered\n");
return 1;
}
book1 = (struct book*)malloc(n * sizeof(struct book));
for (int i = 0; i < n; i++) {
get_info(book1 + i);
display_book(book1 + i);
}
return 0;
}
推荐阅读
- mongodb - Kafka Mongo Sink 连接器,如何将 SMT 时间戳转换器用于 JSON 数组中归档的日期
- rsync - 如何使用 rsync 过滤特定的隐藏“点”文件?
- javascript - 我需要返回 null 作为名为 null 的键的值,但它一直返回未定义
- c++ - C ++:具有初始化列表的默认构造函数
- java - java - 如何在没有扫描仪的Java命令提示符中请求的输入中输入字符串作为值
- c - 在链表程序c中查找重复的数据条目
- html - 在 React.js 中将图像设置为完整背景
- java - 我想避免我拥有的大量 if 语句
- c++ - 引用是从函数右值返回的吗?
- python - 烧瓶 request.files 不在“文件”中