gpt4 book ai didi

c - 如何循环结构体?

转载 作者:行者123 更新时间:2023-11-30 21:01:03 27 4
gpt4 key购买 nike

结构循环

main() 
{
structure perdata //MADE A STRUCTURE
{
char name;
int age;
float salary;
}p1,p2,p3;
int i;
for(i=1;i<4;i++)
{
printf("p%d.name",i);
scanf("%s",);/*should loop and read names of p1,p2,p3*/
}
printf("p1.name:%s",p1.name);
getch();
}

最佳答案

您应该使用结构数组,以便可以迭代它。

示例:学生结构数组,

#include <stdio.h>

struct student{
char name[50];
int roll;
float marks;
};

int main(){
struct student s[10]; //Ten student details maybe stored
int i;
printf("Enter information of students:\n");

//get the details of 10 students
for(i=0;i<10;++i)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}

//display the details of 10 students
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return 0;
}

使用上面的示例代码并编写您的程序。

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

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