【问题标题】:C Programming: Reading from a file and printing on screen - formattingC 编程:从文件中读取并在屏幕上打印 - 格式化
【发布时间】:2016-12-03 03:06:23
【问题描述】:

我正在尝试从文件 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;
}

【问题讨论】:

  • 您应该查看proper C formatting。那里有一些技巧可以使您的代码更易于阅读。

标签: c struct structure


【解决方案1】:

这个:

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, ...

你多余的逗号应该会消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    相关资源
    最近更新 更多