C:读取文本文件并操作数据

标签 c arrays dynamic-programming

我是 C 编程新手。我正在处理以下格式的文本文件

1 2009 詹姆斯·史密斯 2 18

2 2010 鲍勃·戴维斯 5 18

3 2010 艾伦·汤姆森 15 26

4 2010 布拉德·海耶 15 26

我想要做的是读取每一行并以有意义的方式打印到控制台,例如

詹姆斯·史密斯 (James Smith) 于 2009 年首次亮相,年收入 200 万美元。他一生赚了 1800 万,平均每年 xyzM

然后

收入最高者:?
平均收入:?
玩家总数:

这是我到目前为止所拥有的:

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>

typedef char *string;

int main() {

    int i = 0, line = 5;
    char ch[100];
    string array[4];

    FILE *myfile;
    myfile = fopen("C:/Data/Players.txt","r");
    if (myfile== NULL)
    {
        printf("File Does Not Exist \n");
        return 1;
    }

    while(line--)
    {
        fscanf(myfile,"%s",&ch[i]);
        printf("\n%s", &ch[i]);
        array[0] = array[i];
        i++;

        if(i=5)
        {
            printf("Yes");
        }


    }

    fclose(myfile);

    return 0;
}

最佳答案

您应该逐行读取文件,解析字符串,直到遇到文件结尾(EOF)。您只有在阅读完它之后才知道您遇到了它。

这是我的解决方案:

#include <stdio.h>

int main()
{
    FILE *file;
    int line_number;
    int year;
    char fname[10];
    char lname[10];
    int m_a_year;
    int m_over_lifetime;

file = fopen("textfile.txt", "r");

while(!feof(file))
{
    fscanf(file, "%d %d %s %s %d %d", &line_number, &year, fname, lname, &m_a_year, &m_over_lifetime);
    printf("%s %s made his debut in %d and earns %dm a year. He has earned %dm over his lifetime with an average of %dM a year\n\n", fname, lname, year, m_a_year, m_over_lifetime, (m_over_lifetime/(2016-year)));
}

fclose(file);

    return 0;
}

输出:

james smith made his debut in 2009 and earns 2m a year. He has earned 18m over h
is lifetime with an average of 2M a year

bob davies made his debut in 2010 and earns 5m a year. He has earned 18m over hi
s lifetime with an average of 3M a year

Allan Thomson made his debut in 2010 and earns 15m a year. He has earned 26m ove
r his lifetime with an average of 4M a year

Brad Haye made his debut in 2010 and earns 15m a year. He has earned 26m over hi
s lifetime with an average of 4M a year

关于C:读取文本文件并操作数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39425492/

相关文章:

c - C 中的输入验证(和循环)

c -/proc 文件系统挂起我的系统

c - Misra-C 与 X-macros 兼容吗?

c++ - 将字符串分配给指针数组

python - 应用于巨大数组的 numpy array2string,跳过中心值,( ... 在中间)

algorithm - 购买策略的动态规划

正确的 C 头结构

algorithm - 解决优化问题(找到让每个人上下山所需的最短时间)

c - C 中 char 数组的动态内存分配问题

c - 将函数返回的数组分配给二维数组的一行 C 编程