2017-03-11 108 views
0

您好,我對c編程非常陌生。我有以下一段代碼,代碼基本上通過終端從用戶獲取值並打印出值。所以我有一個get函數和打印函數。不知何故,當我輸入學號後,程序停止並直接顯示登記選項提示並輸出姓名和ID。我嘗試重新排列這些選項,然後運行。任何想法的傢伙?在此先感謝無法在C中打印值C

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

#define MAX_LEN 80 

struct Student { 
    char *name;    // point to a name string 
    int id;     // student number 
    char *enroll;    // enrollment option: D or X 
}; 

struct Student student1; 

void getStudent(struct Student *s) 
{ 
    printf("Type the name of the student: "); 
    s->name = malloc(100); // assume name has less than 100 letters 
    fgets(s->name, 100, stdin); 

    printf("\nType the student numner: "); 
    scanf("%d", &(s->id)); 

    printf("\nType the student enrollment option (D or X): "); 
    scanf("%c", (s->enroll)); // some bug here 
    return; 
} 

void printStudent(struct Student s) 
{ 
    char name[MAX_LEN]; 
    char enroll[MAX_LEN]; 
    int id; 

    s.id = id; 
    s.name = name; 
    s.enroll = enroll; 

    printf("Student Details: %d %s %s \n", s.id, s.name, s.enroll); 
    return; 
} 

int main(int argc, char *argv[]){ 
    getStudent(&student1); 
    printStudent(student1); 
    return 0; 
} 
+3

這是一個很好的時間來介紹自己調試 –

+3

'的scanf( 「%C」,(S->報名));'*調用不確定的行爲* - 您還沒有分配任何內存'登記'(或初始化指針) - 也許你打算宣佈'登記'爲'字符登記'(非指針) – UnholySheep

+0

*它的工作* ..那麼你的問題是什麼? – minigeek

回答

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; 
}