fgets 无法正常工作,不接受输入

问题描述 投票:0回答:1

我想输入长度为 80 的字符串,但不幸的是它正在跳过输入。 请建议如何正确使用 fgets() ,我遵循了各种答案但仍然无法正常工作。 我也尝试了另一种方法与出版商但没有运气。

#include<stdio.h>
#define title_max 80
#define publisher_max 20

typedef struct library_book
{
    int id;
    char title[title_max];
    char publisher[publisher_max];
    int code;
    union u
    {
        int no_of_copies;
        char month[10];
        int edition;
    }info;
    int cost;
}book;

int main()
{
    int n;
    printf("\nPlease number of books: ");
    scanf("%d", &n);
    book books[n];
    char title[title_max];
    char publisher[publisher_max];
    for(int i=0;i<n;i++)
    {
        printf("\nPlease enter the ID of the book: ");
        scanf("%d",&books[i].id);
        printf("\nPlease enter the title of the book: ");
        // scanf("%[^\n]%*c",&books[i].title);
        fgets (title,title_max,stdin);
        strcpy(books[i].title, title);
        printf("\nPlease enter the name of publisher: ");
        scanf("%[^\n]%*c",&books[i].publisher);
        
    }

    for(int i=0;i<n;i++)
    {
        printf("\nTitle: %s",books[i].title);
    }
    return 0;
}

输出控制台:

bright@goodman:/mnt/d/VS Code/C$ ./a.out

Please number of books: 1

Please enter the ID of the book: 1

Please enter the title of the book: 
Please enter the name of publisher: 123ewdfcads

Please eneter the cost of book: ''123

Please enter the code of the book: 
Title:
c scanf newline fgets
1个回答
0
投票

问题是在之前调用

scanf

之后
    printf("\nPlease enter the ID of the book: ");
    scanf("%d",&books[i].id);

输入缓冲区包含对应于按下的 Enter 键的换行符

'\n'

所以

fgets
的下一次调用读取一个空字符串。

    fgets (title,title_max,stdin);

你可以使用

scanf
的评论电话

     scanf(" %79[^\n]", books[i].title);

注意格式化字符串中的前导空格。它允许跳过空白字符。

此外,您需要使用表达式

&books[i].title
代替表达式
books[i].title

否则在调用

fgets
之前,您可以插入以下循环

while ( getchar() != '\n' );

从输入缓冲区中删除换行符

'\n'

© www.soinside.com 2019 - 2024. All rights reserved.