C语言结构体数组 的输入方式

Python016

C语言结构体数组 的输入方式,第1张

1、如果从标准输入中输入,只有挨个输入每个结构体对象的成员。如果从文件输入,则可以用fread函数直接读入整个对象。

2、例程:

#include <stdio.h>

struct student

{

int num

char name

int score[3]

}

void main()

{

void print(struct student)

struct student stu[5]

int i

for(i=0i<5i++) //问题在%c前要一个空格,还有少了&

{

scanf("%d %c%d%d%d",&stu[i].num,&stu[i].name,&stu[i].score[0],&stu[i].score[1],&stu[i].score[2])

}

printf("输入完成\n")

for(i=0i<5i++)

print(stu[i])

}

void print(struct student stu)

{

printf("%d%c%d%d%d\n",stu.num,stu.name,stu.score[0],stu.score[1],stu.score[2])

}

number是指针,指向常量字符串,输入的时候,改变的其实是number的空间,也就是出现了野指针,导致程序出错

修改方式很简单,把char*number,改成char number[100]就可以了

只改定义一处,其他的不需要改动

具体大小,取决于你的需求

结构体的输入输出与一般的一样,但是不能整体对结构体进行输入输出,只能对其成员分个输入输出,比如结构体struct

student{

int

number

char

name[20]}..................输入学号可以用scanf("%d",&number)输入姓名scanf("%s",name)........................当然,你也可以使用gets()之类的,只要记住对其成员输入输出就行,纯手打,满意请采纳,谢谢O(∩_∩)O~