Can I use gets() and puts() of same string in different functions

103 views Asked by At

#include <stdio.h>
#include <string.h>

struct employee
{
    char ename[20];
    int sal;
};

struct employee accept(struct employee);
void display(struct employee);

void main()
{
    struct employee e,f;
    f=accept(e);
    display(f);
}

struct employee accept(struct employee e)
{
    printf("Enter employee name and his sal :");
    gets(e.ename);
    gets(e.sal);
}

void display(struct employee e)
{
    printf("Employee name :");
    puts(e.ename);
    printf("Employee salary :");
    puts(e.sal);
} 

The above code is taking the details from the user and not displaying it as it is supposed to do. Can anyone help me out rectifying it?

2

There are 2 answers

2
MikeCAT On

You forgot to return what is read from accept.

struct employee accept(struct employee e)
{
printf("Enter employee name and his sal :");
gets(e.ename);
gets(e.sal);
return e; /* add this to return things read */
}

Also note that:

  • gets() and puts() are for reading and printing strings, not integers. int sal; in the declaration of the structure should be replaced with something like char sal[128];.
  • You should add indentation to improve readability.
  • gets() has unavoidable risk of buffer overrun. It is deprecated in C99 and removed from C11. Instead of that, you should use fgets() and manually remove newline character read.
3
anastaciu On
  1. main should return int. Use int main(void).

  1. sal is an int, gets would be for strings but you shouldn't ever use, it's very dangerous as no destination buffer bounds checks are performed, allowing buffer overflow. Check out this post by SO C queue legend ;)

    Use:

    fgets(e.ename, sizeof e.ename, stdin);
    

    And:

    scanf("%d", &e.sal);
    

    Note that you should always check the return value of these functions to validate inputs.


  1. puts only parameter is a pointer to char, it doesn't take int arguments.

    Use:

    printf("%d", e.sal);
    

  1. Your accept() function should return a struct employee but it doesn't.

    Possible correction:

    struct employee accept(void)
    {
        struct employee e;
        printf("Enter employee name and his sal :");
        if(fgets(e.ename, sizeof e.ename, stdin) != NULL)
        {
            e.ename[strcspn(e.ename, "\n")] = '\0'; // optional, removing \n
        }
        else
        {
            //handle error
        }
        if(scanf("%d", &e.sal) != 1)
        {
            //handle error
        }
        return e;
    }
    

    Usage:

    struct employee e;
    e = accept();
    

    You can remove f as it's not needed.