无法使用结构在C中的数据文件中存储整数值

无法使用结构在C中的数据文件中存储整数值,c,structure,C,Structure,下面给出的代码只正确显示char值,而int值是垃圾值 #include<stdio.h> #include<conio.h> #include<alloc.h> typedef struct { char name[10]; char age[10]; }stu; void main() { FILE *fp=fopen("Demo.bin","wb"); FILE *fr=fopen("Demo.bin","rb");

下面给出的代码只正确显示char值,而int值是垃圾值

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

typedef struct
{
  char name[10];
  char age[10];
}stu;

void main() {
    FILE *fp=fopen("Demo.bin","wb");
    FILE *fr=fopen("Demo.bin","rb");
    stu *ptr;
    int n,i;

    printf("\n How many elements???");
    scanf("%d",&n);
    ptr=(stu *)malloc(sizeof(stu)*n);
    i=0;

    while(i<n)
    {
        scanf("%s%d",ptr->name,ptr->age);
        fseek(fp,sizeof(ptr)*i,SEEK_SET);
        fwrite(ptr,sizeof(ptr),1,fp);
        i++;
    }
    fclose(fp);
    i=0;

    while(i<n)
    {
        fseek(fr,sizeof(ptr)*i,SEEK_SET);
        fread(ptr,sizeof(ptr),1,fr);
        printf("%s%d",ptr->name,ptr->age);
        i++;
    }
    free(ptr);

    fclose(fr);
    getch();

}
#包括
#包括
#包括
类型定义结构
{
字符名[10];
炭龄[10];
}斯图;
void main(){
文件*fp=fopen(“Demo.bin”、“wb”);
文件*fr=fopen(“Demo.bin”、“rb”);
stu*ptr;
int n,i;
printf(“\n有多少个元素?”);
scanf(“%d”和“&n”);
ptr=(stu*)malloc(sizeof(stu)*n);
i=0;
while(iname,ptr->age);
fseek(fp,sizeof(ptr)*i,SEEK_集);
fwrite(ptr,sizeof(ptr),1,fp);
i++;
}
fclose(fp);
i=0;
while(iname,ptr->age);
i++;
}
免费(ptr);
fclose(fr);
getch();
}

代码生成的输出具有正确的字符串值,但为垃圾整数值。

不能对字符数组调用
%d
。您必须首先将字符数组转换为整数,或者您可以将其打印为带有
%s
的字符串,就像您对人名所做的那样。

\include
#include <stdio.h>
#include <stdlib.h> //!
#include <conio.h>

typedef struct {
    char name[10];
    int age; //!
} stu;

int main(){ //!
    FILE *fp=fopen("Demo.bin","wb");
    FILE *fr; //!
    stu *ptr;
    int n,i;

    printf("\n How many elements???");
    scanf("%d", &n);
    ptr=malloc(sizeof(stu)*n);
    i=0;
    while(i<n){
        scanf("%s %d", ptr[i].name, &ptr[i].age); //!
        fwrite(&ptr[i++], sizeof(*ptr), 1, fp); //!
    }
    fclose(fp);
    //memset(ptr, 0, n*sizeof(*ptr)); //!
    free(ptr); //!
    ptr=malloc(sizeof(stu)*n); //!
    fr=fopen("Demo.bin","rb"); //!
    i=0;
    while(i<n){
        fread(&ptr[i], sizeof(*ptr), 1, fr); //!
        printf("%s %d\n", ptr[i].name, ptr[i].age); //!
        ++i;
    }
    free(ptr);
    fclose(fr);
    getch();
    return 0;
}
#包括/! #包括 类型定义结构{ 字符名[10]; 国际年龄;/! }斯图; int main(){/! 文件*fp=fopen(“Demo.bin”、“wb”); 文件*fr;//! stu*ptr; int n,i; printf(“\n有多少个元素?”); scanf(“%d”和“&n”); ptr=malloc(sizeof(stu)*n); i=0;
当(i在
chararter数组中读取
integer
时,编译器可能会发出警告

与下面的示例代码相同

#include <stdio.h>
int main()
{
    char age[10];
    scanf("%d", age);
    printf("out : %d\n", age);
}
输出:

23
out : -1073788814
因此,将字符年龄[10]更改为整数年龄您的代码将正常工作

typedef struct
{
      char name[10];
      int age;
}stu;

这是因为当age在结构中的数据类型为
char[10]时,您将age视为
int
,即一个十个字母的字符串。您没有收到警告吗?
“%d”需要类型为“int*”的参数,但参数的类型为“char*”
请用注释标记您对OP代码所做的更改?这会很有帮助。
typedef struct
{
      char name[10];
      int age;
}stu;