首页 > 解决方案 > 如何在我的 C 程序中多次使用“gets”函数?

问题描述

我的代码:

#include <stdio.h>
#include <math.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char a[10],b[10];
        puts("enter");
        gets(a);
        puts("enter");
        gets(b);
        puts("enter");
        puts(a);
        puts(b);
    }
    return 0;
}

输出:

1

enter 

enter

surya  (string entered by user)

enter

surya   (last puts function worked)

标签: cmemoryruntime-errorruntimegets

解决方案


如何在 C 程序中多次使用“gets”函数?

永远不gets()应该在你的程序中使用。它已被弃用,因为它会导致缓冲区溢出,因为它不可能停止消耗特定数量的字符 - fe 并且主要重要的是 - 缓冲区ab每 10 个字符能够容纳的字符数量。

这里也解释了:

为什么gets函数如此危险以至于不应该使用它?

特别是,在乔纳森莱弗勒的这个回答中。

改为使用fgets()


此外,循环的定义ab内部while没有任何意义,即使很难,这只是一个玩具程序,用于学习目的。

此外请注意,这scanf()会留下换行符,由按下从scanf()调用中返回stdin。你必须抓住这个,否则fgets()之后的第一个会消耗这个角色。


这是更正后的程序:

#include <stdio.h>

int main()
{
    int t;
    char a[10],b[10];

    if(scanf("%d",&t) != 1)
    {
        printf("Error at scanning!");
        return 1;
    }

    getchar();          // For catching the left newline from scanf().

    while(t--)
    {        
        puts("Enter string A: ");
        fgets(a,sizeof a, stdin);
        puts("Enter string B: ");
        fgets(b,sizeof b, stdin);

        printf("\n");

        puts(a);
        puts(b);

        printf("\n\n");
    }

    return 0;
}

执行:

$PATH/a.out
2
Enter string A:
hello
Enter string B:
world

hello

world


Enter string A:
apple
Enter string B:
banana

apple

banana

推荐阅读