0

i am not getting the desired regd_num and name i want regd_num as 567 but it shows 67 and similary in case of name i want raj but it shows C can you please help me how to read the strings properly in an union

#include<stdio.h>

union student{
    int reg;
    char name[20];
    int marks[10];

};

int main()
{
    union student s;
    int i;
    float avg,sum;

    printf("Enter the register number:");
    scanf("%d",&s.reg);
    printf("\nEnter the name:");
    scanf("%s",s.name);
    printf("\nEnter the marks:\n");
    for(i=0;i<3;i++)
    {
        scanf("\n%d",&s.marks[i]);
    }
    sum=s.marks[0]+s.marks[1]+s.marks[2];
    if(s.marks[0]>=0&&s.marks[1]>=0&&s.marks[2]>=0)
    {
        if(s.marks[0]>=40&&s.marks[1]>=40&&s.marks[2]>=40)
        {
            avg=sum/3;
            printf("\nRegd.No:%d",s.reg);
            printf("\nName:%s",s.name);
            printf("\nPercentage: %0.2f",avg);
        }
        else
            printf("Grade is Failed");
    }
    else
        printf("Invalid mark. Mark should between 0-100");
}
Barmar
  • 669,327
  • 51
  • 454
  • 560
  • 2
    a `union` can hold **one** of its fields at a time, you're looking for a `struct`... –  Apr 21 '18 at 15:37
  • and while at it, `scanf("%s", ...)` is a guaranteed buffer overflow, always use field widths (like in your case, assuming you made `student` a `struct`, use `scanf("%19s", s.name);` -- or better use functions like `fgets()`) –  Apr 21 '18 at 15:38
  • even more problems not **directly** related: 1.) using `scanf()` without checking the return value is dangerous, and here, your program will "go wild" if any input doesn't meet your expectations. I recommend my [beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) to get some better ideas. 2.) `float` -- don't use it if you don't have a good reason (and there aren't many good reasons) -- use `double` instead. –  Apr 21 '18 at 15:46
  • can you make some changes and send back the code it's pretty urgent – Kalapala Teja Apr 21 '18 at 15:56
  • I'm not here to do your "urgent" homework. Take the time and learn, it will help you. Your immediate question should already be answered: you need a `struct` here, not a `union`. –  Apr 21 '18 at 15:58
  • thanks @Yunnosch for the dupe link explaining the core issue asked about here :) –  Apr 21 '18 at 16:05

0 Answers0