1

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.

KWJ2104
  • 1,959
  • 6
  • 38
  • 53

2 Answers2

1

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);
}
  • Ah thank you, this works for the ctrl+d thing. However, it doesn't print the line I just typed in. It seems like stdin wasn't cleared or something so it keeps adding the printouts together every loop. – KWJ2104 Oct 30 '11 at 00:52
  • It works on my computer, except for the fact it chops up lines(due to the second argument of 5 to fgets). –  Oct 30 '11 at 00:53
  • Yep, changing the second argument to 100 makes it work perfectly. –  Oct 30 '11 at 00:54
  • Oh yeah my mistake. It seems to work when the characters are under 5 but whenever its over 5 the output is kind of weird. I just want it to print the first 5 chars of my input every time. I guess I can deal without that and just parse the input later anyways. Thanks again. – KWJ2104 Oct 30 '11 at 00:57
  • Looking at the specs for printf, this is what you want then. http://codepad.org/DCJHqwnU –  Oct 30 '11 at 01:00
  • feof is [evil](http://stackoverflow.com/questions/5431941/in-c-is-while-feof-always-wrong) – hugomg Oct 30 '11 at 01:18
0

You shouldn't need to worry about "detecting" ctrl-D, as that is a shell thing that isn't seen by your program. You should consider using input redirection while you fix the code before worrying about the ctrl-D thing

./myExecutable < inputFile
hugomg
  • 68,213
  • 24
  • 160
  • 246