简体   繁体   English

使用结构写入文件

[英]writing in a file using structures

I wrote a code that is supposed to write into a file but when i execute the program it says "error in saving student data".Here is the code. 我写了一个应该写入文件的代码,但是当我执行程序时,它显示“保存学生数据时出错”。这是代码。

#include<stdio.h>

typedef struct Student{
 int numberOfStudents;
 char name; // onoma foithth
 char surname; // epi8eto foithth


};


int main(){
    struct Student  s1; 
    FILE *file=fopen("d:\\student.txt","w");
    if(file==NULL){
        printf("error in saving student data");
        return 1;
    }
    while(1){

    printf("Enter number of students: ");
    scanf("%d",&s1.numberOfStudents);
    printf("enter name: ");
    scanf("%s",&s1.name);
    printf("enter surname: ");
    scanf("%s",&s1.surname);

    fprintf(file,"%d\t%s\t%s\n",s1.numberOfStudents,s1.name,s1.surname);
    printf("continue (Y/N)");
    char ch=getch();
    if (ch=='N' || ch=='n')
    break;
    }


    fclose(file);
    return 0;
}

I have searched but i can't find the problem.where is my mistake? 我已经搜索过,但是找不到问题。我的错误在哪里?

name field of structure should be char array if you want to store onoma foithth in that as shown. 如果要在其中存储onoma foithth ,则结构的name字段应为char array ,如下所示。 modify your structure as 修改您的结构为

typedef struct Student{
 int numberOfStudents;
 char name[10]; // onoma foithth
 char surname; // epi8eto foithth


};

and then while scanning name remove & because name is itself address. 然后在扫描name删除&因为name本身就是地址。

scanf("%s",s1.name);

Make sure you gave correct path in fopen() 确保您在fopen()给出了正确的路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM