char到int(结构和文件)

时间:2017-09-09 15:28:12

标签: c

我如何将char复制到int以使用此程序在C中进行数学计算。

我已经写了一个包含字段namesnameage的文件。

档案示例:

Antonio Giannini 14
Mimmo Cava 22
Luck Santo 33

代码:

struct contact {
    char name[20];
    char sname[20];
    char age[20];
};
struct contact users[MAX];

/**
 * Read the file.
 */
void read() {
    FILE *f;
    i = 0;
    f = fopen("file.txt", "r");

    if (fopen == NULL) {
        printf("The file does not exist");
    } else {
        system("cls");
        while (!feof(f)) {
            fscanf(f,"%s", users[i].name);
            fscanf(f,"%s", users[i].sname);
            fscanf(f,"%s", users[i].age);
            i++;
        }
        fclose(f);
    }
}

/**
 * Prints the content.
 */
void stamp() {
    system("cls");
    printf("%-10s%-10s%-10s\n\n", "name", "sname", "age");
    for (j=0; j < i-1; j++) {
        printf("%-10s%-10s%-10s\n\n", users[j].name, users[j].sname, users[j].age);
    }
}

代码到现在为止,但是,现在我如何才能只使用age进行数学计算,如总数或平均值,或者最老和最年轻的数学计算?

1 个答案:

答案 0 :(得分:0)

很简单 - int total_age = atoi(user [0] .age)+ atoi(user [1] .age)等等,直到最后一条记录。

如果你想这样做,你可以使用itoa()将整数转换为字符串。 请使用以下read()函数。

void read() {
    FILE *f;
    int total_age = 0;
    int i = 0;
    f = fopen("file.txt", "r");

    if (f == NULL) {
        printf("The file does not exist");
    } else {
        system("cls");
        while (!feof(f)) {
            fscanf(f,"%s %s %d", users[i].name,users[i].sname,users[i].age);
            total_age = total_age + (users[i].age);
            i++;
        }
        printf("Total age is %d",total_age);
        fclose(f);
    }
}

并按如下方式更改结构 -

 struct contact {
        char name[20];
        char sname[20];
        int age;
    };
相关问题