Search code examples
cinputstdinfgets

Loop For User Input


I would like to write a program that keeps asking for user input until I break out of it with ctrl+D. Here is what I have:

char input[100];
while(input != EOF){
       printf("Give me a sentence:\n");
       fgets(input, 5, stdin);
       printf("your sentence was: %s\n", input);
}

I would like the fgets to start over with the first 5 characters of the new input, not like the 6th of the last input whenever it loops around, and I also do not know how to write the condition on the while to break it out through ctrl+D. Right now as you can see input (which is a char[] is being compared to EOF).

Thanks for any advice.


Solution

  • I think you are looking for the function feof.

    char input[100];
    while(!feof(stdin)){
           printf("Give me a sentence:\n");
           fgets(input, 5, stdin);
           printf("your sentence was: %s\n", input);
    }