我基本上有一个包含学生信息的结构。在接受最后一个输入后,它崩溃了。最后一个 printf 从未出现,我的编译器也没有发现任何错误。
struct stud_prof {
char student_name[NAME_LIMIT];
char ssn_number[SSN_LIMIT];
double gpa;
int units;
char major_code;
} student1;
int main(void)
{
printf( "What is the student's name?\n" );
scanf(" %s", &student1.student_name);
fflush(stdin);
printf( "What is the student's Social Security number?\n" );
scanf(" %s", &student1.ssn_number);
fflush(stdin);
printf( "What is the student's GPA?\n" );
scanf(" %lf", &student1.gpa);
fflush(stdin);
printf( "How many units has the student completed?\n" );
scanf(" %d", &student1.units);
fflush(stdin);
printf( "Enter the student's Major Code.\n" );
scanf( " %s", &student1.major_code);
printf( " %s, %s, %f, %d, %s ", student1.student_name,
student1.ssn_number, student1.gpa, student1.units, student1.major_code);
return 0;
}
最佳答案
请注意,fflush(stdin);
是未定义的行为,但它很可能不是问题的原因。
这是错误的:
printf( "Enter the student's Major Code.\n" );
scanf( " %s", &student1.major_code);
printf( " %s, %s, %f, %d, %s ", student1.student_name,
student1.ssn_number, student1.gpa, student1.units, student1.major_code);
格式说明符与参数不匹配。
您正在使用 %s
表示 student1.major_code
,它是 char
而不是 char*
。
使用 %c
代替:
printf( "Enter the student's Major Code.\n" );
scanf( " %c", &student1.major_code);
printf( " %s, %s, %f, %d, %c", student1.student_name,
student1.ssn_number, student1.gpa, student1.units, student1.major_code);
关于c - 为什么这个简单的程序会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45147360/