I am trying to read a file test.txt via fscanf and store it in a array of struct. I have posted the code that I have tried. Looks like problem here is with load function
This is what I have in test.txt:
205,11.20,John Snow
336,23.40,Winter is coming
220,34.20,You know nothing
load function uses loadinput function to read test.txt file into the “item” array and sets the target of the “NoPtr” to the number of Items read from the file (which in this case should be 3).
After reading the file, I am also trying to print it on screen, but it won't work. Nothing is displayed at all.
This program compiles. What is it that I am doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
double value;
int unit;
char name[50];
};
int load(struct Item* item, char Name[], int* NoPtr);
int loadinput(struct Item* item, FILE* data);
void display(struct Item item, int variableA);
int main(void)
{
struct Item FIN[3];
int i, n;
load(FIN, "test.txt", &n);
for (i = 0; i < n; i++)
{
display(FIN[i],0);
}
return 0;
}
int load(struct Item* item, char Name[], int* NoPtr)
{
struct Item ARR[3];
int flagcheck;
FILE* fl;
fl = fopen("Name[]", "r");
while (fl)
{
flagcheck = loadinput(&ARR, fl);
if (flagcheck < 0)
{
fclose(fl);
break;
}
else
{
*NoPtr++;
}
fclose(fl);
}
return 0;
}
int loadinput(struct Item* item, FILE* data)
{
int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 2) {
return -1;
}
fgets(item->name, sizeof item->name, data);
item->name[strlen(item->name)-1] = '\0';
return 0;
}
void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}
答案 0 :(得分:0)
请参阅修复演示 - BLUEPIXY
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
double value;
int unit;
char name[50];
};
int load(struct Item* item, char Name[], int* NoPtr);
int loadinput(struct Item* item, FILE* data);
void display(struct Item item, int variableA);
int main(void) {
struct Item FIN[3];
int i, n;
load(FIN, "test.txt", &n);
for (i = 0; i < n; i++) {
display(FIN[i],0);
}
return 0;
}
int load(struct Item* item, char Name[], int* NoPtr){
*NoPtr = 0;
int flagcheck;
FILE* fl;
fl = stdin;//fopen(Name, "r");//for ideone
while (fl){
flagcheck = loadinput(&item[*NoPtr], fl);
if (flagcheck < 0){
fclose(fl);
break;
} else {
++*NoPtr;
}
}
return 0;
}
int loadinput(struct Item* item, FILE* data){
int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 2) {
return -1;
}
fgets(item->name, sizeof item->name, data);
item->name[strlen(item->name)-1] = '\0';
return 0;
}
void display(struct Item item, int variableA){
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}