【问题标题】:How do I receive an input from scanf and make numbers of structures accordingly?如何从 scanf 接收输入并相应地制作结构数量?
【发布时间】:2021-05-01 17:35:42
【问题描述】:

我想接收来自键盘的输入,例如: 输入国家数量:

我的结构是

struct country {
  char name[20];
  int population;
  float area;
  float gdp;
  char continent[20];
}

如果用户键入 3,我想要其中的 3 个结构。如何申报?

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    您从用户输入中读取数字,然后在运行时创建相应数量的结构:

    #include <stdlib.h>
    #include <stdio.h>
    
    struct country {
        char name[20];
        int population;
        float area;
        float gdp;
        char continent[20];
    };
    
    int main(int argc, char *argv[]){
        unsigned int count;
        scanf("%u", &count); //read count
        struct country *countries = calloc(sizeof(struct country), count); //allocate memory for count country structs
        countries[0].area = 1.0f; //now you can access the structs like array elements
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多