【问题标题】:Family members structure ,C家庭成员结构,C
【发布时间】:2018-10-02 17:28:09
【问题描述】:

我是一名学生,我们的一项家庭作业是用 C 语言编写一个程序,该程序具有两种结构:一种用于家庭,一种用于个人(如下所示)。 我们应该获取包括姓名和 ID 在内的家庭成员信息,然后使用动态分配名称字段(在个人结构中)将其打印出来。

这是我的代码,但它出了点问题。它不允许我继续处理母亲的详细信息...我的意思是,它跳过了您需要插入姓名的部分,直接进入“ID”。 我试图添加“flushall”,但它似乎不起作用。代码可能还有更多我不知道的问题,因为我仍在试图找出这个代码有什么问题:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
    char* name;
    long id;
}person;

typedef struct Family {
    person dad;
    person mom;
    int numOfKids;
    person* pointers[10];
}family;

void readDate(person* t);
void printData(person* t);
void readFamily(family* f);
void printFamily(family* f);

void main()
{ 
    family ff;
    readFamily(&ff);
    printFamily(&ff);
    free(ff.dad.name);
    free(ff.mom.name);
    for (int i = 0; i < ff.numOfKids; i++)
        free(ff.pointers[i]->name);

}
void readDate(person* t)
{
    int size;
    char names[200];
    printf("Please enter a name\n");
    _flushall;
    gets_s(names);
    size = strlen(names);
    t->name = (char*)calloc(1, sizeof(names + 1));
    t->name = names; 
    printf("Please enter ID\n");
    scanf("%d", &t->id);
}
void printData(person* t)
{
    printf("%s %d\n", t->name, t->id);
}
void readFamily(family* f)
{
    (f->numOfKids) = 0;
    int countinue = 1;
    char c;
    printf("Please enter the father's info\n");
    _flushall;
    readDate(&(f->dad));
    printf("Please enter the mother's info\n");
    _flushall;
    readDate(&(f->mom));
    do {
        printf("Would u like to add a child? Y/N\n");
        _flushall;
        scanf("%c", &c);
        if (c == 'N' || c == 'n')
        {
            countinue = 0;
        }
        else
        {
            printf("Pleae enter the child's info:\n");
            readDate((f->pointers[f->numOfKids]));
            f->numOfKids++;
        }
    } while (countinue &&f->numOfKids <= 10);
}
void printFamily(family* f)
{
    printf("The family's parents info:\n");
    printf("Mom:%s ID:%d\t Dad:%s ID:%d\n", f->mom.name, f->mom.id, f->dad.name, f->dad.id);
    if (f->numOfKids == 0)
        printf("There are no children!\n");
    else
    {
        for (int i = 0; i < f->numOfKids; i++)
        {
            printf("#%d:Name:%s ID:%d\n", i + 1, f->pointers[i]->name, f->pointers[i]->id);
        }
    }
    printf("\n");
}

【问题讨论】:

标签: c struct scanf


【解决方案1】:

在您的代码中使用rewind(stdin) 而不是flushall,因为flushall 在VS 中是过时的函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    相关资源
    最近更新 更多