首页 > 解决方案 > 如何在数组中使用类型转换来分隔数据?

问题描述

我想在同一个大小为 100x4 的数组中添加 2 种不同的类型。在第一列中,我想添加食物的名称(使用指针),在第二列和第三列中添加一些数字,例如卡路里和进食时间(使用类型转换)。

我已经尝试了很多天,但我找不到任何解决方案。有没有办法通过类型转换来解决这个问题?

#include <stdio.h>
int main(){
    char *table[100][4];
    int n=0;
    int j;
    for (j=0;j<4;j++){
        if (j==0){
            printf ("Add your food:\n");
            scanf("%c",&table[n][j]);
        }else if (j==1){

            printf ("Add calories:\n");
            (float) *table[n][j];
            scanf("%d",&table[n][j]);

        }else if (j==2){
            (float) *table[n][j];
            printf ("Add the time you ate:\n");
            scanf("%.2f",&table[n][j]);
        }else if (j==3){
            printf ("Kati\n");
        }
    }
    for (j=0;j<4;j++){
        if (j==0){
            printf ("food:%c",&table[n][j]);
        }else if (j==1){
                        (float) *table[n][j];

            printf ("calories:%f",*table[n][j]);
        }else if (j==2){
                        (float) *table[n][j];

            printf ("time you ate:%f",*table[n][j]);
        }else if (j==3){
            printf ("Kati\n");
        }
    }
}

标签: cpointerstypescasting

解决方案


当您想要将多个不同的数据视为一个单元时,您将使用 astruct并拥有一个结构数组。

您可以将结构定义为:

struct food {
    char name[50];
    int calories;
    float time;
};

并像这样使用它:

struct food table[100];
int n=0;

for (n=0; n<100; n++) {
    printf ("Add your food:\n");
    scanf("%49s",table[n].name);

    printf ("Add calories:\n");
    scanf("%d",&table[n].calories);

    printf ("Add the time you ate:\n");
    scanf("%f",&table[n].time);
}

for (n=0; n<100; n++) {
    printf("food:\n");
    printf("  name: %s\n", table[n].name);
    printf("  calories: %d\n", table[n].calories);
    printf("  time: %.2f\n", table[n].time);
}

推荐阅读