[英]C Programming: Reading from a file and printing on screen - formatting
我正在嘗試從文件test.txt中讀取內容並將其顯示在屏幕上。 這是我的test.txt文件中的內容:
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;
}
這個:
fscanf(Dfile, "%d,%d,%d,%lf,%d", &item->unit, &item->quant, &item->minquant,
&item->value, &item->isTx);
掃描5個數字和4個逗號字符,在輸入緩沖區中保留“,Name”。 那就是逗號開頭的地方。
更改為:
fscanf(Dfile, "%d,%d,%d,%lf,%d,", &item->unit, ...
並且您的多余逗號應該消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.