c - 如何在 c 用户定义函数中返回 "struct"数据类型?

标签 c struct gets

我需要读取5个城市名称,我的代码有什么问题,请解释 我不想使用 void 数据类型

//read the 5 city using struct
struct census
{
    char city[20];
    int popullation;
    float literacy;
};

struct census citi[5];
struct census read(struct census citi[]);

main()
{
   int i;
   citi= read(citi);
   for(i=0;i<5;i++)
   {
       printf("%s",citi[i].city);
       printf("\n");
   }
}

struct census read(struct census citi[])
{
    int i;
    for(i=0;i<5;i++)
        gets(citi[i].city);

    return(citi);
}

如何使用数据类型 struct 返回值,请发现错误并解释错误

最佳答案

您的程序不要求您从 read() 函数返回任何内容。不要调用自己的函数read(),因为那是标准函数的名字,所以这样定义会更好

void readCities(struct census *citi, size_t count)
{
    size_t index;
    for (index = 0 ; index < count ; index++)
     {
        fgets(citi[i].city, sizeof(citi[i].city), stdin);
     }
}

main()

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

struct census
{
    char city[20];
    int popullation;
    float literacy;
};
void readCities(struct census *citi);

int main()
{
   size_t        index;
   struct census citi[5];

   readCities(citi, sizeof(citi) / sizeof(*citi));
   for (index = 0 ; index < 5 ; index++)
    {
       printf("%s\n", citi[index].city);
    }
   return 0;
}

上面的代码将初始化 struct,如您所见,您不需要全局变量,除非您真的知道自己在做什么,否则不要使用全局变量,如 @ Weather Vane在下面评论,你可以检查 fgets() 的返回值并返回成功读取结构的数量,而不是根本不返回,就像这样

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

struct census
{
    char city[20];
    int popullation;
    float literacy;
};
size_t readCities(struct census *citi);

int main()
{
   size_t        index;
   struct census citi[5];
   size_t        count

   count = readCities(citi, sizeof(citi) / sizeof(*citi));
   for (index = 0 ; index < count ; index++)
    {
       printf("%s\n", citi[index].city);
    }
   return 0;
}

size_t readCities(struct census *citi, size_t count)
{
    size_t index;
    size_t successfulCount;

    successfulCount = 0;
    for (index = 0 ; index < count ; index++)
     {
        if (fgets(citi[i].city, sizeof(citi[i].city), stdin) != NULL)
            successfulCount += 1;
     }

    return successfulCount;
}

关于c - 如何在 c 用户定义函数中返回 "struct"数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28919776/

相关文章:

c - 给出段错误和 idk 在哪里

c - 用普通 C 将文本文件读入数组

c - 为什么 gets() 不起作用而 scanf() 在这里起作用

c - C 代码中的局部变量对齐

c - 指向 C 中结构的指针的工作示例

c - GETS - C 不适合我

c - 从目标文件中删除特定符号

C结构体: typedef Doubt !

c - fscanf 转 int 和数组

c - 为什么 gets() 读取的字符比我在用 calloc() 初始化它时设置的限制更多?