fread()在在线编辑器和本地机器(C++)上的不同行为

Different behaviour of fread() on online editor and the local machine (C++)

本文关键字:C++ 在线 编辑器 fread 机器      更新时间:2023-10-16

当我在C++代码中使用fread()并在在线编辑器上编译它(使用gcc)时,它工作得很好。但是,当我在本地机器上运行相同的代码时,它会无限等待,除非我在windows PC上点击ctrl+z。为什么会这样?

我正在读取代码中的stdin(如果这有帮助的话)。

这是代码(但不是我的。我只是用它来理解它)。

#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
#define size 65536
int main()
{
char b[size];
int t=0,n,k,cnt=0;
int c,j;
scanf("%d %dn",&n,&k);
printf("%d %dn", n, k);
while((c = fread(b,1,size,stdin))>0)
{
     printf("%dn",c);
           for(j=0;j<c;j++)
           {
            if(b[j]=='n')
            {
                          if(t%k==0)cnt++;
                          t = 0;
            }
            else
            {
                          t = (t*10) + (b[j]-'0');                
            }              
           }
 }
printf("%dn",cnt);    
return 0;
}

它一直读到输入流的末尾。

在线编辑器通过管道传输来自文件(或类似文件)的输入流,并在所提供的输入的末尾结束。

您的本地机器从控制台读取它(除非您将某些内容通过管道传输到程序中),直到您使用Ctrl-Z关闭输入流,它才会结束。