gpt4 book ai didi

c - 如何打印结构体的成员?

转载 作者:行者123 更新时间:2023-11-30 18:11:38 24 4
gpt4 key购买 nike

我编写了以下程序来输入学生的凭据,然后打印它们。但是,当我输入完两个学生的记录(允许输入的最大记录数)时,它不会打印它们。这是程序。有人能指出错误吗?谢谢。

#include<stdio.h>
#include<string.h>

struct student
{
char name[20];
char mobile_no[10];
char class[5];
};

int main()
{
static struct student s[2];
int m=0,n=0,i;
char c;
printf("Enter the name , mobile_no and class of the students\n");
while((scanf("%c",&s[m].name[n]))!= EOF)
{
for(n=0; n<=19; n++)
scanf("%c",&s[m].name[n]);
for(n=0; n<=9; n++)
scanf("%c",&s[m].mobile_no[n]);
for(n=0; n<=4; n++)
scanf("%c",&s[m].class[n]);
scanf("%c",&c); //scans for the newline character \n
n = 0;
m++;
}

for(i=0 ; i<m ; i++)
{
printf("%s%3s%3s\n",s[i].name,s[i].mobile_no,s[i].class); //prints the structure
}
}

最佳答案

我不做家庭作业,但你很幸运。请记住,您输入的长度不能超过结构字符串中声明的长度 - 1. 自己进行审查、释放等。

struct student
{
char name[20];
char mobile_no[10];
char _class[5];
};

int read_students(struct student *s)
{
int m = 0;
printf("Enter the name , mobile_no and class of the students. Name == exit for exit\n");
while (1)
{
char tmp[20];
printf("Name: ");
scanf("%s", tmp);
if (!strcmp(tmp, "exit")) break;
if ((s = (struct student *)realloc(s, sizeof(struct student) * (m + 1))) == NULL) {m = -1; break;}
strcpy(s[m].name, tmp);
printf("Mobile: ");
scanf("%s", s[m].mobile_no);
printf("Class: ");
scanf("%s", s[m]._class);

m++;
}

if (m != -1)
{
printf("Number of students: %d\n", m);

for (int i = 0; i<m; i++)
{
printf("%s %3s %3s\n", s[i].name, s[i].mobile_no, s[i]._class);//prints the structure
}
}
return m;
}

在主函数中:

struct student *s = NULL;
int numberofstudentds;

numberofstudentds = read_students(s);

关于c - 如何打印结构体的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45632870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com