2017-08-16 37 views
0

gets(edu.classes [i] .students [j] .name);结构 - 为什么得到函数不能比较scanf?

我想知道为什么编译器跳过这一行后调试,并没有输入名称?这种方式调用gets函数是否合法?

注意:一旦我使用scanf(“%s”,...) - 它的工作原理!

scanf(“%s”,edu.classes [i] .students [j] .name);

(我知道我没有释放内存分配和检查,如果分配没有失败! - 我知道这是必要这只是时间问题):)

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

#define SIZE 20 

typedef struct 
{ 
char name[SIZE]; 
int id; 
}Student; 

typedef struct 
{ 
Student *students; 
int num_students; 
char teacher[SIZE]; 
}Class; 

typedef struct 
{ 
Class *classes; 
int num_classes; 
}Education; 

int main() 
{ 
int i, j; 
Education edu; 
puts("how many classes?"); 
scanf("%d", &(edu.num_classes)); 
edu.classes = (Class*)malloc((edu.num_classes) * sizeof(Class)); 
if (edu.classes == NULL) 
{ 
    printf("ERROR allocation\n"); 
    exit(1); 
} 
for (i = 0; i < edu.num_classes; i++) 
{ 
    puts("enter num of students"); 
    scanf("%d", &(edu.classes[i].num_students)); 
    edu.classes[i].students = (Student*)malloc((edu.classes[i].num_students) 
* sizeof(Student)); 
    for (j = 0; j < edu.classes[i].num_students; j++) 
    { 
     puts("enter student's name"); 
     gets(edu.classes[i].students[j].name); // this is the problematic line 
     puts("enter id"); 
     scanf("%d", &(edu.classes[i].students[j].id)); 
    } 
} 
return 0; 
} 
+2

_never_使用'gets'。 –

+0

我会推荐使用'fgets'而不是'gets',它的容易出错的 –

+0

表示,我不知道为什么这不起作用。使用'scanf(“%19s”...)'来防止缓冲区溢出 –

回答

0

我认为这是看到由于按下Enter键而产生的换行符。然后gets停止阅读。尝试在gets看到它们之前尝试吃那些特殊字符。或者使用scanf和%s,它可以像你看到的那样吃任何领先的空白。

+0

你是指fflush? –

+0

其实我的意思是从标准输入中读取字符,直到它不再是像换行符那样的特殊字符(\ n)。 –

+0

好吧......你给了我一个主意:) 我只是写了这个命令行两次。 –

相关问题