有没有办法在使用循环或任何其他情况下停止以前的工作输入?

is there any way to stop the previous working inputs during using a loop or in any other case?

当我在一个循环中使用 fgets 时,它将之前的工作输入命令作为输入并对其进行处理,这种情况不仅发生在我身上,而且发生在许多其他情况下,所以我的问题是...... .

1.Is有没有办法在开始任何循环时停止之前的工作命令?

2.if 不是,请告诉我如何解决这个问题?

程序

#include <stdio.h>
#include <strings.h>

struct student
{
    char name[10];
}st[10];


int main()
{
    int i,j;
    printf("enter the number of students=");
    scanf("%d",&i);
    j=i;

    for (i=1;i<=j;i++)
    {
        printf("enter the student's name= ");
        fgets(st[i].name,sizeof(st[i]),stdin);
        printf("%s",st[i].name);
    }

}

输出

enter the number of students=2                                                                     
enter the student's name=                                                                          
enter the student's name= hello                                                                    
hello    

看到这里它从第二行获取输入,即它把第一个输入作为回车键并转移到第二个输入

使用 fflush("stdin");在 fgets 之前 它将清除包含“enter”或“/n”的输入缓冲存储器。 因为,scanf 有遇到 space 后停止接受输入的行为。 所以它在缓冲存储器中留下了“enter”或“/n”。

您可以通过使用 fflush 刷新标准输入缓冲区来完成...请参见下面的代码:

#include <stdio.h>
#include <strings.h>

struct student
{
    char name[10];
}st[10];


int main()
{
    int i,j;
    printf("enter the number of students=");
    scanf("%d",&i);
    j=i;

    for (i=1;i<=j;i++)
    {
        
        fflush(stdin); // flush the stdin buffer

        printf("enter the student's name= ");
        fgets(st[i].name,sizeof(st[i]),stdin);
        printf("%s",st[i].name);
    }
    return 0;
}

输出为:

enter the number of students=2
enter the student's name= hello
hello
enter the student's name= world
world

使用fflush(stdin)的问题:

虽然fflush(stdin)可行,但实际上并不是完美的解决方案。 fflush(stdin) 有一些潜在的问题。请看一下here。在 online gdb 的情况下,fflush(stdin) 根本不起作用。

因此,我提出了一种替代解决方案。它在 online gdb 和您的本地电脑上都能完美运行:

问题是输入数字末尾的uneaten '\n'。这保存在 stdin 的缓冲区中。所以,我们只需要吃它。所以,我们只写一个scanf("%d%c", &i, &uneaten_newline_char)。完整代码:

#include <stdio.h>
#include <strings.h>

struct student
{
    char name[10];
} st[10];


int main()
{
    char uneaten_newline_char;
    int i,j;
    printf("enter the number of students=");
    scanf("%d%c", &i, &uneaten_newline_char); // notice, there's no space between '%d%c', they must be written without any space between them
    j=i;

    for (i=1;i<=j;i++)
    {
        
        // fflush(stdin); // flush the stdin buffer

        printf("enter the student's name= ");
        fgets(st[i].name, sizeof(st[i]), stdin);
        
        printf("%s",st[i].name);
    }
    return 0;
}

这个解决方案可能看起来有点难看...但这比使用 fflush(stdin) 好。但对我来说,最漂亮、最完美的解决方案是使用您自己的 reader 函数。创建您自己的 readline 函数。并根据需要在末尾处理空格和换行符。 c 的内置函数在这种情况下肯定不是很好。