Thread: Confused about fgets, clearing the buffer, etc

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    Confused about fgets, clearing the buffer, etc

    Good day...

    In order to analyze how the fgets function works, I wrote this little program:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char line[10];
        fgets(line, sizeof(line), stdin);
        
        printf("%sworld", line);
        
        getchar();
      
        return 0;
    }
    This is how I understand this: if I type something with eight characters and hit enter, fgets will read the eight characters plus the \n and put a \0 at the end. Am I correct? The getchar() function forces me to hit enter again to exit the program because there's nothing in the input buffer.

    Now if I type something with nine characters, will fgets read the nine characters, put a \0 at the end of the array and put leave the \n in the input buffer? Am I correct here?

    I am wondering now what would be a good way to take care of this in a, let's say, menu loop.
    I was thinking about creating a function something along the following lines
    Code:
    void get_rid_of_newline(char line[])
    {
        int c;
        char *ptr;
        if((ptr = strchr(line, '\n')) != NULL)
            *ptr = '\0';
    
        else
            while((c = getchar()) != '\n' && c != EOF)
                ;
    }
    and use right after each user input. What do you have to say about all of this? Thanks for your comments and suggestions.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > fgets will read the eight characters plus the \n and put a \0 at the end. Am I correct?
    Yes.

    > put a \0 at the end of the array and put leave the \n in the input buffer? Am I correct here?
    Yes.

    > I was thinking about creating a function something along the following lines
    Indeed - something fairly similar to that is in the FAQ.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Clearing Buffer Problem (beginners Q)
    By Iconate in forum C Programming
    Replies: 5
    Last Post: 03-18-2008, 01:57 PM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. buffer contents swapping
    By daluu in forum C++ Programming
    Replies: 7
    Last Post: 10-14-2004, 02:34 PM
  4. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 05:15 AM
  5. Validating the contents of a char buffer
    By mattz in forum C Programming
    Replies: 3
    Last Post: 12-09-2001, 06:21 PM