我想从文件中读取数据以输入结构,但打印出错误。所以我已经解决了
fscanf()
的问题一段时间了,但我仍然无法解决。有人可以帮我解决吗?
这里是完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct INFOR
{
int STK;
char HOTEN[50];
int SD;
} INFOR;
#define max 100
typedef INFOR A[max];
void input(INFOR A[n] , int &n);
int main() {
int n;
INFOR A[n];
input(A , n);
free(A);
}
void input(INFOR A[n] , int &n) {
char filename[50];
char line[max];
int i = 0;
/*printf("Nhap ten file: ");
gets(filename);
fflush(stdin);*/
FILE *file = fopen("C:/Users/DELL/Desktop/VanBan.txt" , "r");
if(file == NULL) {
printf("Khong mo duoc file");
return ;
}
fgets(line , sizeof(line) , file);
fseek(file , strlen(line) , SEEK_SET);
A = (INFOR*)malloc(n * sizeof(INFOR));
printf("%-15s %-20s %-10s\n" , "So Tai Khoan" , "Ho Va Ten" , "So Du");
while(fgets(line, max , file) != NULL)
{
fscanf(file , "%-15d %-20s %-10d \n", &A[i].STK, A[i].HOTEN, &A[i].SD);
printf("%-15d %-20s %-10d \n" , A[i].STK , A[i].HOTEN , A[i].SD);
i++;
fflush(stdin);
}
n = i + 1;
fclose(file);
}
这里的
fscanf()
可能不起作用。它的问题是它无法从文件中正确读取数据。
例如:
- 来自文件的数据:
So Tai Khoan Ho va Ten So du
200 Ashley Graham 1
我的程序输出:
So Tai Khoan Ho Va Ten So Du
12522576 538976366
538976288 538976366
0
我试图删除
"-15"
,"-20"
,"-10"
在fscanf()
但无济于事。还是打印错了。从那以后我不知道它是怎么读的。