首页 > 解决方案 > 当结构指针传递给函数时,为什么 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;
}

标签: cxcode

解决方案


您的代码有几个问题。你混合scanffgets然后你忘记了它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;
}

推荐阅读