从格式化的文本文件中获取行到行的输入

凸轮

我正在制作一个需要能够从以特定方式设置格式的文本文件中加载数据的应用程序。例如...

James, 2, 7.000000, 1000.000000, 0.000000, 0.000000
Tony, 7, 7.000000, 1000.000000, 0.000000, 0.000000
Michael, 2, 7.000000, 1000.000000, 0.000000, 0.000000
David, 2, 7.000000, 1000.000000, 0.000000, 0.000000

当前,我正在尝试使它能够使程序读取文件并在控制台中输出

1. James
2. Tony
3. Michael
4. David

为了达到这个目的,我尝试了以下方法...

(我用来存储数据的结构)

struct userSession {
    char name[20];
    int unitType;
    float amountPaid;
    float amountPurchased;
    float returnInvestment;
    float personalAmount;
    float personalPercent;
};

在main()中

FILE *fp;
struct userSession user;
int counter = 1;

if( (fp = fopen("saves.dat", "r")) == NULL ) {
    puts("File cannot be opened!");
}
else {
    while(!feof(fp)) {
        fscanf(fp, "%[^ \t\n\r\v\s,]%*c %d %f %f %f %f", &user.name, &user.unitType, &user.amountPurchased, &user.amountPaid, &user.personPercent, &user.returnInvestment);
        printf("%d. %s\n", counter, user.name);
        counter++;
    }
}

这导致无限的while循环。我假设没有任何东西可以读取第一个文件,因此永远不会到达EOF,但是我可能是错的。

谁能提供一些有关如何实现此目标的见解?我已经阅读了fseek / fwrite / fread,但是它们似乎没有输出/输入纯文本,例如我要使用的输入文件。

最终,一旦我使该列表生效,系统将提示用户从列表中进行选择以加载所需的数据。

谢谢,卡姆

用户名

由于字段之间用逗号分隔,因此可以使用。fscanf将返回成功读取的字段数。
19将防止
在%19中的空格之前的名称中写入太多字符,因为它是一个数组,因此" %19将跳过前几行的换行符,因此不需要&号
user.name

while( ( fscanf(fp, " %19[^,], %d, %f, %f, %f, %f", user.name, &user.unitType, &user.amountPurchased, &user.amountPaid, &user.personPercent, &user.returnInvestment)) == 6) {
    printf("%d. %s\n", counter, user.name);
    counter++;
}

就像@ameyCU在另一个答案中提到的那样,现在更好了吗?
使用fgets从文件中读取每一行,然后使用sscanf来获取字段。

char line[100];//or larger if needed
while ( fgets ( line, sizeof ( line), fp)) {
    if ( ( sscanf(fp, "%19[^,], %d, %f, %f, %f, %f", user.name, &user.unitType, &user.amountPurchased, &user.amountPaid, &user.personPercent, &user.returnInvestment)) == 6) {
        printf("%d. %s\n", counter, user.name);
        counter++;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章