Thread: Endless fgets()

  1. #1
    Registered User
    Join Date
    Feb 2021

    Question Endless fgets()

    My fgets function never stops, although I set the limit to the string length that is excepted.

    char string[100];
    case 1: {
       //scanf(" %s",string);
       while (getchar() != '\n') {
       fgets(string, 99,stdin);
    I am trying to replace the commented scanf with the same thing but that would allow spaces.
    I have never been using fgets, but I have read that it stops when sees the newline or end of file(not this case).

    Can anyone suggest what could be the problem?

    Thank you!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    I would suggest that the problem is not fgets, but what comes before fgets:
    while (getchar() != '\n') {
    My guess is that you wrote this to remove anything left on the previous line of input, including the ending newline. Trouble is, if there is an odd number of characters remaining before that ending newline, this will consume them, and then wait for one more character of input. So if you then have input that you expect to be read by fgets, this loop will then read that input too, and keep reading all the way until the newline... and if there is an odd number of characters before that ending newline, it will then wait for one more character of input, so your fgets call doesn't get run, or if it does get run, it waits for input, thereby looking like it "never stops".

    What you could do instead is this:
    while (getchar() != '\n');
    making the assumption that you won't encounter end-of-file (which can be triggered manually or perhaps the input is piped from file), but it may be better to consistently stick with fgets throughout, and use sscanf when you need scanf-style parsing.
    Last edited by laserlight; 03-08-2021 at 07:51 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help with this endless loop
    By xkohtax in forum C Programming
    Replies: 4
    Last Post: 05-01-2009, 02:32 PM
  2. cin >> buf endless loop
    By cfriend in forum C++ Programming
    Replies: 2
    Last Post: 10-07-2005, 04:01 PM
  3. Endless loop!
    By Paninaro in forum C Programming
    Replies: 3
    Last Post: 06-23-2002, 08:15 PM
  4. help with endless loop
    By haus in forum C Programming
    Replies: 4
    Last Post: 04-10-2002, 08:31 AM

Tags for this Thread