你对c编程很新。我有以下代码,代码基本上通过终端从用户获取值并打印出值。所以我有一个get函数和print函数。不知何故,当我输入学生ID后,程序停止并直接显示注册选项提示并打印出名称和ID。我尝试重新排列选项,然后它工作。伙计们好吗?提前致谢
i
答案 0 :(得分:0)
请参阅代码中的更正。 http://ideone.com/BQjS1A
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 80
// **** Add a constant for the size of name
#define MAX_NAME 100
struct Student {
char name[MAX_NAME]; // ** Save the hassle using malloc
int id; // student number
char enroll; // *** Just need a character - not a character pointer
};
struct Student student1;
void getStudent(struct Student *s)
{
printf("Type the name of the student: ");
// *** Do not need malloc as using an array
// s->name = malloc(100); // assume name has less than 100 letters
fgets(s->name, MAX_NAME, stdin);
printf("\nType the student number: "); // ** Corrected a typo
scanf("%d", &(s->id)); // *** You should check the return value here and take appropriate action - I leave that you the reader
printf("\nType the student enrollment option (D or X): ");
// *** Added a space in front of %c to read white space
scanf(" %c", &(s->enroll)); // scanf requires a charcter pointer here
// return; This is not needed
}
void printStudent(struct Student s)
{
// *** THIS CODE DOES NOT MAKE ANY SENSE
// char name[MAX_LEN];
// char enroll[MAX_LEN];
// int id;
// s.id = id;
// s.name = name;
// s.enroll = enroll;
// *** Need %c to print enroll
printf("Student Details: %d %s %c \n", s.id, s.name, s.enroll );
/// return; Not needed
}
int main(int argc, char *argv[]){
getStudent(&student1);
printStudent(student1);
return 0;
}