0

I'm trying to read in inputs from the terminal, I want to stop reading inputs if there is a blank line and enter is pressed. Here is what I have at the moment.

#include <stdio.h>
#include <string.h>

   int main(int argc,char const *argv[]){
       char input[1024];

       while(fgets(input,1024,stdin)!=NULL){
          printf("%s", input);
       }
       if(EOF){
          printf("EOF");
       }

        return 0;
}
halo2x2
  • 33
  • 1
  • 7
  • 3
    Your code will *always* print `"EOF"`, since `EOF` is, per the standard, non-zero and fixed. Checking for an empty line (single newline only) is trivial. `while(fgets(input,1024,stdin)!=NULL && *input != '\n')` , but that won't solve your issue following the while-loop. – WhozCraig Nov 14 '18 at 00:10
  • 1
    Look up what `fgets` returns on success and end-of-file. It is really well documented behavior. – Jongware Nov 14 '18 at 00:11
  • 4
    I don't think I have ever seen someone try `if(EOF)` before ... congratulations on finding something new to try in C – M.M Nov 14 '18 at 00:19
  • When you don't use command line arguments in the program, the appropriate form for the definition of `main()` is `int main(void)`. – Jonathan Leffler Nov 14 '18 at 00:23
  • 2
    Where you have `if (EOF)` is, interestingly, one of the few places where it might be appropriate to use `feof()` instead: `if (feof(stdin)) printf("EOF\n"); else if (ferror(stdin)) printf("ERR\n"); else assert("can't happen" == 0);` would be correct. Beware though: [Why is `while (!feof(file))` always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Jonathan Leffler Nov 14 '18 at 00:26

1 Answers1

2

One easy thing that you could do is to check the length of the string read in by fgets. The newline character at the end of the input string is considered a valid character by fgets. That means that the length of the string you're testing would be 1 if you just entered a newline So, you want to move the test inside the loop instead of trying to test for EOF outside of the loop. So, your code should look like this:

#include <stdio.h>
#include <string.h>

int main(void) {
    char input[1024];

    while(fgets(input,1024,stdin)!=NULL) {
        printf("%s", input);
        if(strlen(input) == 1) {
            printf("EOF\n");
            break;
        }
    }
    return 0;
}

Also note, to get the EOF test to work you wouldn't hit enter, instead you'd send the end of file key, like CTRL-D on linux to your program. In this case you wouldn't have a strlen test inside the loop.

bruceg
  • 2,433
  • 1
  • 22
  • 29