我是学生,我们的任务之一就是在C上编写一个有两种结构的程序:一个用于家庭,一个用于人(如下所示)。 我们应该获取包括姓名和ID在内的家庭成员信息,然后使用名称字段的动态分配(在人员结构中)打印它。
继承我的代码,但是它出了问题。我不会让我继续处理母亲的详细信息......我的意思是,它会跳过你需要插入名称的部分,直接进入& #34; ID&#34 ;. 我试图添加" 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");
}
答案 0 :(得分:0)
在您的代码中使用rewind(stdin)
代替flushall
,因为flushall
在VS中是过时的功能