fflush(stdin)的工作如何更改以下代码中的输出? [英] How is the working of fflush(stdin) changing the output in below code?

查看:108
本文介绍了fflush(stdin)的工作如何更改以下代码中的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int main()
{
        int test_no ,count=1,i,n,j;
        scanf("%d",&test_no);
        fflush(stdin);
        int arr1[test_no];
        for(i=0;i<test_no;i++)
        {
                scanf("%d",&n);
                printf("\n");
                int arr[n];
                for(j=0;j<n;j++)
                {
                        fflush(stdin);
                        scanf("%d",&arr[i]);
                }
                for(j=1;j<=n-1;j++)
                {
                        if(arr[j-1]>arr[j])
                        {
                                count++;
                        }
                }
                if(n==1)
                {
                        arr1[i]=1;
                }
                else
                {
                        arr1[i]=count;
                }
                count=1;
        }
        for(i=0;i<test_no;i++)
        {
                printf("%d\n",arr1[i]) ;
        }
        return 0;
}

此解决方案适用于此问题.

在第三种情况下,我没有获得所需的输出,根据我将fflush(stdin)放在scanf("%d",arr[i])之前还是scanf("%d",arr[i])之后,它给出的输出为3或4,请将此代码告诉问题./p>

I am not getting the desired output for the third case , it's giving me output as 3 or 4 depending on whether I place fflush(stdin) before scanf("%d",arr[i]) or after scanf("%d",arr[i]) , please tell the problem with this code .

推荐答案

no 一种神奇的方式.

首先,fflush(stdin);调用未定义行为. 请勿使用.

First of all, fflush(stdin); invokes undefined behavior. Don't use that.

引用C11,第§7.21.5.2章, fflush函数(强调我的)

Quoting C11, chapter §7.21.5.2, The fflush function (emphasis mine)

如果stream指向最新的输出流或更新流 没有输入操作,fflush函数会导致该流的任何未写数据 交付给主机环境以写入文件; 否则,该行为是 未定义.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

那是

for(j=0;j<n;j++)
{
    fflush(stdin);
    scanf("%d",&arr[i]);
}

对我来说似乎很不对劲,arr[i]不能保证在范围之内.应该是

looks pretty wrong to me, arr[i] is not guaranteed to be within bounds. It should rather be

scanf("%d",&arr[j]);

这篇关于fflush(stdin)的工作如何更改以下代码中的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆