0
我想從文件test.txt中讀取並在屏幕上顯示它。 這是我在我的test.txt文件:C編程:從文件讀取並在屏幕上打印 - 格式化
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
我曾嘗試這個代碼,一切似乎除了我得到一個額外的「」當我在我的屏幕打印是工作。這是在屏幕上打印的內容:
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 |
我真的在這裏碰到一堵磚牆。不知道這個額外的「,」在哪裏打印。我如何擺脫上面的「,」? 這是我的代碼:
#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;
}
你應該看看[適當的C格式](// prohackr112.tk/r/proper-formatting)。這裏有一些技巧可以讓你的代碼更易於閱讀。 –