Reputation: 89
I am trying to read from a file test.txt and display it on screen. This is what I have in my test.txt file:
22,100,22,44.44,0,Jon Snow
32,208,42,55.94,0,You know nothing
23,54,103,36.96,0,Winter is coming
I have tried this code and everything seems to be working except that I am getting an extra "," when I print on my screen. This is what gets printed on screen:
1| 22| ,Jon Snow | 44.44| 100 | 22 |
2| 32| ,You know nothing | 55.94| 208 | 42 |
3| 23| ,Winter is coming | 36.96| 54 | 103 |
I am really hitting a brick wall here. Not sure where this extra "," is printed. How do I get rid of "," above? This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
double value;
int unit;
int isTx;
int quant;
int minquant;
char name[21];
};
struct Item MI[4];
int NoR = 3;
void display(struct Item item, int nline);
void list(const struct Item item[], int Ntems);
int load(struct Item* item, char Name[], int* PtR);
void InvSys(void);
int menu(void);
int main(void)
{
InvSys();
list(MI, NoR);
return 0;
}
void display(struct Item item, int nline)
{
if (nline == 0)
{
printf("|%3d| %-21s |%6.2lf| %3d | %4d | \n", item.unit, item.name, item.value, item.quant, item.minquant);
}
else
{
//something
}
}
void list(const struct Item item[], int Ntems)
{
int k;
for (k = 0; k < Ntems; k++)
{
printf("%6d", k + 1);
display(item[k], 0);
}
}
int loadItem(struct Item* item, FILE* Dfile)
{
int ret = fscanf(Dfile, "%d,%d,%d,%lf,%d", &item->unit, &item->quant, &item->minquant, &item->value, &item->isTx);
if (ret != 5) {
return -1;
}
fgets(item->name, sizeof item->name, Dfile);
item->name[strlen(item->name)-1] = '\0';
return 0;
}
void InvSys(void)
{
int variable;
load(MI, "test.txt", &variable);
}
int load(struct Item* item, char Name[], int* PtR)
{
*PtR = 0;
int ret;
FILE* varr;
varr = fopen(Name, "r");
while (varr)
{
ret = loadItem(&item[*PtR], varr);
if (ret < 0)
{
break;
}
else
{
++*PtR;
}
}
fclose(varr);
return 0;
}
Upvotes: 0
Views: 46
Reputation: 213656
This:
fscanf(Dfile, "%d,%d,%d,%lf,%d", &item->unit, &item->quant, &item->minquant,
&item->value, &item->isTx);
scans 5 numbers and 4 comma characters, leaving ",Name" in the input buffer. That's where the leading comma comes from.
Change it to:
fscanf(Dfile, "%d,%d,%d,%lf,%d,", &item->unit, ...
and your extra comma should disappear.
Upvotes: 2