如何在结构正确地使用与fgets? [英] How to use fgets properly in a structure?

查看:112
本文介绍了如何在结构正确地使用与fgets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能工作了什么是我的code中的问题。这里是我的code:

I can't work out what's the problem with my code. Here's my code:

#include <stdio.h>
#include <stdlib.h>    

#define N 20

typedef struct _dog {
    char dogName[N],ownerName[N];
    int dogAge;
} Dog;

int main() {
    //Dynamic array
    int size;
    printf("Number of dogs: ");
    scanf("%d", &size);
    Dog *dog = (Dog*)malloc(sizeof(Dog)*size);
    printf("\n");
    //Input
    int i;
    printf("Please provide the data: [dogName][ownerName][dogAge] :\n");
    for(i=0;i<size;i++) {
        fgets(dog[i].dogName, sizeof(dog[i].dogName), stdin);
        fgets(dog[i].ownerName, sizeof(dog[i].ownerName), stdin);
        scanf("%d", &dog[i].dogAge);
    }
    //Output
    printf("\nYou provided the following data:\n");
    for(i=0;i<size;i++) {
        printf("Dog Name: %s\nOwner Name: %s\nDog Age: %d\n", dog[i].dogName, dog[i].ownerName, dog[i].dogAge);
    }

    free(dog);
    return 0;
}

的任务是pretty容易,你必须做出一个数据库,但狗和业主可以有两个或多个名称,所以这就是为什么我尝试使用fget。但输出看起来可怕:(和第一狗名部分通常是空白)

The task is pretty easy, you have to make a database but the dogs and owners can have two or more names, so that's why i try to use fget. But the output looks awful: (And the first Dog name part is usually blank)

You provided the following data:
Dog Name: 

Owner Name: Doggy 1

Dog Age: 0
Dog Name: Big Dick

Owner Name: 2

Dog Age: 0

我读过<一个href=\"http://stackoverflow.com/questions/21138246/how-to-implement-gets-or-fgets-while-using-structure-pointer\">this但并没有帮助我。

我使用的输入:

Doggy 1
Big Dick
2
Doggy 2

它的小狗2.结束后

It's ended after Doggy 2.

推荐答案

您从您的最后一个 scanf函数留下一个换行符()这是一个的有效与fgets输入()。更改

You are leaving a newline from your last scanf() which is a valid input for the fgets(). Change

scanf("%d", &size);

scanf("%d%*c", &size);

消耗和丢弃的结尾的换行由于的preSS <大骨节病>进入狗的数量后,输入键。

to consume and discard the trailing newline due to the press of enter key after entering the number of dogs.

这同样适用于在 dogAge 变量扫描,也罗布泊内。

The same goes for the dogAge variable scanning, too, inside the lop.

这篇关于如何在结构正确地使用与fgets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆