2017-08-16 66 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

好吧......你給了我一個主意:) 我只是寫了這個命令行兩次。 –