小兵 发表于 2015-9-23 11:11:10

文件处理问题

输入框不能停止结束,不知道原因,代码如下:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 4

struct student
{
        char name;
        int phone;
        char addr;
}stu;

void main()
{
        int i;
       
        printf("Please input the student's name phone and address: \n");
       
        for(i=0; i<SIZE; i++)
        {
                scanf("%s %d %s",&stu.name,&stu.phone,&stu.addr);
        }
       
        save();
        system("pause");
}

void save()
{
        FILE *fp;
        int i;
       
        if(!(fp = fopen("student.txt","wb")))
        {
                printf("Cannot find the file!\n");
                return;
        }
       
        for(i=0; i<SIZE; i++)
        {
               
                if( fwrite(&stu,sizeof(struct student),1,fp) != 1)
                {
                        printf("File write error!\n");
                        fclose(fp);
                }
                                               
        }
                       
}

小兵 发表于 2015-10-8 15:53:43

怎么没人指点一下?我运行以后输入的是5组数组元素,不明白???{:5_94:}

andalousie 发表于 2015-10-8 18:14:29

我输入的是四组啊,没有问题吧
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4

struct student {
char name;
int phone;
char addr;
} stu;

void save()
{
FILE *fp;
int i;

if(!(fp = fopen("student.txt","wb"))) {
    printf("Cannot find the file!\n");
    return;
}

for(i=0; i<SIZE; i++) {

    if( fwrite(&stu,sizeof(struct student),1,fp) != 1) {
      printf("File write error!\n");
      fclose(fp);
    }

}

}

void main()
{
int i;

printf("Please input the student's name phone and address: \n");

for(i=0; i<SIZE; i++) {
    scanf("%s %d %s",&stu.name,&stu.phone,&stu.addr);
}

save();
system("pause");
}
页: [1]
查看完整版本: 文件处理问题