归档结构/ C.

时间:2012-05-14 10:21:57

标签: c file struct

填写信息后我收到错误。我不知道我在哪里弄错了。我想通过结构获取信息然后保存在biodata.txt文件中。这只是为了启动我的程序然后我将添加“删除编辑搜索“选项。

#include <stdio.h>
#include <conio.h>

struct biodata{
       int recno,age;
       char name[20],sex;
       float salary;
}obj;

int main(){
    int addData();
    int showRecord();
    char choice;

    while(1){
        printf("\n\n*****CHOOSE YOUR CHOICE*****\n");
        printf("1) ADD DATA\n");
        printf("2) SHOW RECORD\n");
        printf("Enter your choice : ");

        choice = getche();
        switch(choice){
            case '1' :  
                addData();
                break;
        }
    }
}

int addData(){
     FILE *fp;
     fp = fopen("biodata.txt","w+");

     printf("\n*****ADDING DATA*****\n");
     printf("\nEnter Record No : ");
     scanf("%d",&obj.recno);
     printf("Enter Name : ");

     scanf("%s",obj.name);
     printf("Enter age : ");
     scanf("%d",&obj.age);

     printf("Enter Sex : ");
     scanf("%s",obj.sex);

     printf("Enter Salary : ");
     scanf("%f",&obj.salary);
     fwrite(&obj,sizeof(obj),1,fp);

     fclose(fp);
}

1 个答案:

答案 0 :(得分:3)

你在做:

printf("Enter Sex : ");
scanf("%s",obj.sex);

但是obj.sex是char类型:

struct biodata{
        int recno,age;
        char name[20],sex;
        float salary;
}obj;

将scanf更改为:

scanf("%c",&obj.sex);