2016-02-04 129 views
0

在下面的代碼scanf()的工作從用戶,但與fgets()獲取名稱不工作請別人幫助我理解爲什麼它不工作爲什麼fgets()不在這裏工作?

#include <stdio.h> 
#include <stdlib.h> 
typedef struct university{ 
    int roll_no; 
    char name[16]; 
}uni; 
int main() 
{ 
    uni *ptr[5],soome;char i,j=0; 
    for(i=0;i<5;i++) 
    { 
     ptr[i]=(uni*)calloc(1,20); 
     if(ptr[i]==NULL) 
     { 
      printf("memory allocation failure"); 
     } 
     printf("enter the roll no and name \n"); 
     printf("ur going to enter at the address%u \n",ptr[i]); 
     scanf("%d",&ptr[i]->roll_no); 
     //scanf("%s",&ptr[i]->name); 
     fgets(&ptr[i]->name,16,stdin); 
    } 
    while(*(ptr+j)) 
    { 
     printf("%d %s\n",ptr[j]->roll_no,ptr[j]->name); 
     j++; 
    } 
    return 0; 
} 
+0

你得到的錯誤是什麼? – Shaan

回答

-1

首先,fgets(char *s, int n, FILE *stream)需要三個參數:指針s到字符數組的開始,計數n和輸入流。
在原始應用程序中,您使用地址運算符&來獲取指針而不是name[16]數組的第一個元素,而是指向其他地方(要使用地址運算符,則應該引用數組中的第一個字符:name[0]) 。

您在應用程序中使用了很多幻數(例如,20作爲uni結構的大小)。在我的示例中,我儘可能使用sizeof。
鑑於您使用的是calloc,我已經使用了第一個參數是大小等於第二個參數的元素數量,以便一次預先分配所有五個uni結構。

最後的結果是:

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

#define NUM_ITEMS (5) 
#define NAME_LENGTH (16) 

typedef struct university{ 
    int roll_no; 
    char name[NAME_LENGTH]; 
} uni; 

int main() 
{ 
    uni *ptr; 
    int i; 

    ptr = (uni*)calloc(NUM_ITEMS, sizeof(uni)); 
    if(NULL == ptr) { 
    printf("memory allocation failure"); 
    return -1; 
    } 

    for(i=0; i<NUM_ITEMS; i++) { 
    printf("enter the roll no and name \n"); 
    printf("You're going to enter at the address: 0x%X \n",(unsigned int)&ptr[i]); 
    scanf("%d",&ptr[i].roll_no); 
    fgets(ptr[i].name, NAME_LENGTH, stdin); 
    } 
    for(i=0; i<NUM_ITEMS; i++) { 
    printf("%d - %s",ptr[i].roll_no,ptr[i].name); 
    } 

    free(ptr); 
    return 0; 
} 

注:我已經加入到free(ptr);調用提供免費應用程序和不同的返回碼年底通過calloc分配的內存,如果它是不可能的分配內存。