从 C 中的标准输入读取到 EOF



我正在使用Unix机器,我正在尝试从控制台读取,直到达到EOF(我提供Ctrl + D(。我正在使用fread_unlocked,对于输入读取,它输出读取整数相关,但不是正常退出,而是在EOF上给出分段错误。如何修改我的代码以使其按预期运行?

int MAXX = 10000000;
char *ipos, InpFile[MAXX];
inline int input_int(int flag=0)
{
  while(*ipos<=32)
    ++ipos;
 if(flag)
    return(*ipos++-'0');
 LL x=0,neg=0;
 char c;
 while(true)
  {
    c=*ipos++;
    if(c=='-')
        neg=1;
    else
    {
        if(c<=32)
         return neg?-x:x;x=(x<<1)+(x<<3)+c-'0';
    }
  }
 }
int main()
{
   ipos = InpFile;
   fread_unlocked(InpFile, MAXX, 1, stdin);
   while(true){
   int n = input_int();
   printf("%dn",n);
   }
   return 0;
}   

我从控制台输入的是:3 4 5 6Ctrl+D 我现在得到的输出是:3 4 5 6 Segmentation Error预期产出:3 4 5 6谢谢。

fread_unlocked返回

实际读取的字节数。您需要获取该返回值,并且需要确保永远不会尝试使用超过InpFile的字符。例如,如果在全局范围内声明max_ipos,则可以编写:

size_t bytes_read = fread_unlocked(InpFile, 1, MAXX, stdin);
// check for errors
max_ipos = &InpFile[bytes_read];

然后input_int将需要检测何时ipos == max_ipos并在读取*ipos之前终止。

编辑添加:请注意(在乔纳森·莱夫勒的建议下(我将参数的顺序切换1MAXX fread_unlocked。这是因为您要读取大小为 1 的对象,而不是大小为 MAXX 的对象。

顺便说一下,这个:

inline int input_int(int flag=0)

无效 C. 参数的默认值是C++事。(也许有C编译器支持它作为扩展 - 我不知道 - 但肯定有C编译器不支持。

你的代码很脏的代码,大家一读就看了,肯定会搞糊涂的,所以,我清理你的代码:

#include <stdio.h>
#include <iostream>
using namespace std;
int MAXX = 10000000;
char x = 0 ; 
char *ipos = &x, InpFile[10000000];
inline int input_int(int flag=0){
  while( *::ipos <= 32 )
    ++::ipos;
  if(flag)
     return(*::ipos++) -'0';
  char x = 0 , neg = 0;
  char c = ' ';
  while ( true ) {
      c = (*::ipos++);
      if(c == '-')
          neg = 1;
      else {
          if(c <= 32)
              return neg ? -x : x; 
          x = (x << 1) + (x << 3) + c -'0';
      }
  }
}
int main(){
   ipos = InpFile;
   fread_unlocked(InpFile, MAXX, 1, stdin);
   while ( true ) {
       int n = input_int();
       printf( " %d n " , n);
   }
   return 0;
}   

顺便说一下,你没有提到你的程序的工作。你的另一个问题:你没有初始化你的IPOS指针。如果要使用指针,请不要忘记初始化它们。

最新更新