0

我只是对 C 中的基本流处理感到困惑。即使经过一个小时的谷歌搜索和阅读这个问题,我也并不聪明(这不是我第一次尝试深入研究这个问题)。我正在尝试从输入中读取数字,直到达到 EOF 或非数字并能够区分这 2 个。据我了解,这应该可行,但feofandferror条件永远不会成立。这是为什么 ?有人可以为我提供一个有效的代码片段以及一个虚拟的友好深入解释吗?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int number;
  printf("number or EOF:\n");

  while(scanf("%d",&number) == 1)
  {
          printf("read number %d\n",number);
  }
  if(ferror(stdin))printf("error reading\n");
  else if (feof(stdin))printf("eof reached\n");
  return 0;
}
4

1 回答 1

0

我理解流行为的问题源于一个小特性。我不知道在 Windows 控制台中有一个新的不友好的歧义,如果你输入像12 23 ^Z/enter/这样的输入,Ctrl+Z 可以读取为 ASCII 0x1A,但是当你执行12 23 /enter/时被读取为正确的 EOF ^Z/输入/。这段代码解决了这个问题

#include <stdio.h>
#include <stdlib.h>

int main()
{


 printf("int or eof\n");
    int num;
    while( scanf("%d",&num) ==1 )
    {
        printf("the read number is  %d \n",num);
    }
    if(!feof(stdin) && getchar()!=0x1A)//first check if its read as EOF,
          //if it fails, call getchar for help to check for ^Z
    {
        printf("non-int error\n");
    }
    else printf("eof ok\n");
    system("PAUSE");
    return 0;

我很抱歉这个误导性的问题。

于 2013-11-27T21:31:46.417 回答