我可以在不同的函数中使用相同字符串的gets()和puts()吗

问题描述


#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);
} 

上面的代码是从用户那里获取详细信息,而不是按预期显示它。谁能帮我纠正一下?

解决方法

  1. main 应该返回 int。使用 int main(void)

  1. sal 是一个 intgets 将用于字符串,但你永远不应该使用,这是非常危险的,因为没有执行目标缓冲区边界检查,允许缓冲区溢出。查看 SO C 队列图例的 this post ;)

    使用:

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

    还有:

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

    请注意,您应该始终检查这些函数的返回值以验证输入。


  1. puts 唯一的参数是一个指向 char 的指针,它不需要 int 参数。

    使用:

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

  1. 您的 accept() 函数应该返回一个 struct employee,但它没有。

    可能的更正:

    struct employee accept(void)
    {
        struct employee e;
        printf("Enter employee name and his sal :");
        if(fgets(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;
    }
    

    用法:

    struct employee e;
    e = accept();
    

    您可以删除 f,因为它不需要。

,

您忘记返回从 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 */
}

还要注意:

  • gets()puts() 用于读取和打印字符串,而不是整数。结构声明中的 int sal; 应替换为类似 char sal[128]; 的内容。
  • 您应该添加缩进以提高可读性。
  • gets() 有不可避免的缓冲区溢出风险。它在 C99 中被弃用并从 C11 中删除。相反,您应该使用 fgets() 并手动删除换行符读取。