2017-04-01 37 views
0
#include <stdio.h> 
#include <conio.h> 
struct personal 
{ 
    char name[20]; 
    int day; 
    char month[12]; 
    int year; 
    float salary; 
}; 
void main() 
{ 
     struct personal person;/*Name of structure is personal*/ 
     printf("Enter name of employee"); 
     scanf("%s",&person.name); 
     printf("\nEnter day of joining"); 
     scanf("%d",&person.day); 
     printf("\nEnter month of joining"); 
     scanf("%s",&person.month); 
     printf("\nEnter year of joining"); 
     scanf("%d",&person.year); 
     printf("\nEnter salary of employee"); 
     scanf("%f",&person.salary); 
     printf("\nThe details are as follows\n"); 
     printf("Name of employee-%s\n",person.name); 
       ("Date of joining-%d %s 
        %d\n",person.day,person.month,person.year); 
       ("Salary of employee-$%f",person.salary); 
    getch();} 

上述代碼是否正確?在C中學習結構的最佳方法是什麼? 如何結合結構和功能?爲什麼編譯器要求同時加入的日期,月份和年份?

回答

0

因爲在輸入員工姓名的同時要求全部三個,您輸入「空格」,但名稱是char數組,並且如果使用scanf,則會跳過其他輸入。 所以最好使用「gets()」函數。所以代碼看起來像 -

#include <stdio.h> 
#include <conio.h> 
struct personal 
{ 
    char name[20]; 
    int day; 
    char month[12]; 
    int year; 
    float salary; 
}; 
void main() 
{ 
     struct personal person;/*Name of structure is personal*/ 
     printf("Enter name of employee"); 
     /*Replace this line - scanf("%s",&person.name); by*/ 
     gets(person.name); 
     printf("\nEnter day of joining"); 
     scanf("%d",&person.day); 
     printf("\nEnter month of joining"); 
     scanf("%s",&person.month); 
     printf("\nEnter year of joining"); 
     scanf("%d",&person.year); 
     printf("\nEnter salary of employee"); 
     scanf("%f",&person.salary); 
     printf("\nThe details are as follows\n"); 
     printf("Name of employee-%s\n",person.name); 
       ("Date of joining-%d %s 
        %d\n",person.day,person.month,person.year); 
       ("Salary of employee-$%f",person.salary); 
    getch();} 
相關問題