c - C 中的结构体数组

标签 c arrays structure

我是 C 新手,我正在尝试运行我书中的一个程序,该程序展示了我们如何处理结构数组。

    #include<stdio.h>
    #include<conio.h>

struct employee
{
    int empno;
    char name[30];
    int basic;
    int hra;
};

void main()
{
    struct employee e[50];
    int i, j, n; 
    int net[50];
    float avg;

    printf("Enter the number of employees: ");
    scanf("%d", &n);
    printf("Enter Emp. No. \tName:\tBasic\tHRA of each employee in the order.\n");
    for(i=0; i<n; i++)
    {

        scanf("%d", &e[i].empno);
        gets(e[i].name);
        scanf("%d", &e[i].basic);
        scanf("%d", &e[i].hra);

    net[i]=e[i].basic + e[i].hra ;
    avg = avg + net[i];
    }

    avg = avg/n;

    printf("Emp. No \t Name-Netpay: ");
    for(i=0; i<n; i++)
    {
        if(net[i]>avg)
        {
            printf("\t",e[i].empno);
            printf("\t", e[i].name);
            printf("\t", net[i]);
        }    } }

我还有其他模块,可以继续计算平均值并打印那些工资+小时高于平均水平的元素。但是,上面粘贴的代码无法按预期工作。

现在,如果我输入员 worker 数 - 假设为 1,它只允许我输入员工编号和姓名并退出循环。我期望它至少完成一个值为 1 的循环。

对此的任何建议都将受到高度赞赏,如果我在任何地方搞砸了,我深表歉意。谢谢。

最佳答案

在使用 gets 之前,您需要刷新输入中的行(顺便说一句,这已被弃用):

#include <stdio.h>

struct employee
{
    int empno;
    char name[30];
    int basic;
    int hra; 
};

int main()
{
    struct employee e[50];
    int i, j, n; 
    int net[50];
    float avg;

    printf("Enter the number of employees: ");
    scanf("%d", &n);
    printf("Enter Emp. No. \tName:\tBasic\tHRA of each employee in the order.\n");
    for(i=0; i<n; i++)
    {

        scanf("%d", &e[i].empno);
        char c;
        while ((c = getchar()) != EOF && c != '\n');

        gets(e[i].name);
        scanf("%d", &e[i].basic);
        scanf("%d", &e[i].hra);

        net[i]=e[i].basic + e[i].hra ;
        avg = avg + net[i];
    }
    return 0;
}

这是因为 scanf 不会读取行尾 (\n),但 gets 会读取并立即返回。 scanf 将读取名称。基本上,这是一团糟:)。

关于c - C 中的结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301209/

相关文章:

php - 拉拉维尔 5.7 : Detecting duplicates in a collection based on multiple keys (done) but how to move dupes to another collection?

java - 将子类分配给每个数组元素(运行时类型)

c++ - HBITMAP/BITMAP 到 BITMAPINFOHEADER -> 通过网络 -> BITMAPINFOHEADER 到 HBITMAP/BITMAP

java - 如何使用java中的列表结构确定java中当前元素之后是否存在另一个元素

c - LD_PRELOAD 是否可能只影响主可执行文件?

javascript - 为什么在 JavaScript 中将对象插入另一个数组后,我的对象会变成数组?

c - 什么时候指向同一个对象的指针相等?

python - 使用基本算法开始 Python 麻烦

c - 从队列中删除偶数

c - Linux 操作系统中的 MQ 连接