ProbIem with EOF in C

后端 未结 7 744
既然无缘
既然无缘 2021-01-01 03:48

I\'m writing a program which is supposed to read two strings that can contain line breaks and various other characters. Therefore, I\'m using EOF (Ctrl-Z or Ctrl-D) to end t

相关标签:
7条回答
  • 2021-01-01 04:35

    Rather than stopping reading input at EOF -- which isn't a character -- stop at ENTER.

    while((c = getchar()) != '\n')
    {
        if (c == EOF) /* oops, something wrong, input terminated too soon! */;
        a[x] = c;
        x++;
    }
    

    EOF is a signal that the input terminated. You're almost guaranteed that all inputs from the user end with '\n': that's the last key the user types!!!


    Edit: you can still use Ctrl-D and clearerr() to reset the input stream.

    #include <stdio.h>
    
    int main(void) {
      char a[100], b[100];
      int c, k;
    
      printf("Enter a: "); fflush(stdout);
      k = 0;
      while ((k < 100) && ((c = getchar()) != EOF)) {
        a[k++] = c;
      }
      a[k] = 0;
    
      clearerr(stdin);
    
      printf("Enter b: "); fflush(stdout);
      k = 0;
      while ((k < 100) && ((c = getchar()) != EOF)) {
        b[k++] = c;
      }
      b[k] = 0;
    
      printf("a is [%s]; b is [%s]\n", a, b);
      return 0;
    }
    
    $ ./a.out
    Enter a: two
    lines (Ctrl+D right after the next ENTER)
    Enter b: three
    lines
    now (ENTER + Ctrl+D)
    a is [two
    lines (Ctrl+D right after the next ENTER)
    ]; b is [three
    lines
    now (ENTER + Ctrl+D)
    ]
    $
    0 讨论(0)
提交回复
热议问题