Thread: fgets help?

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    1

    fgets help?

    I new to C and I'm learning how to get input for strings.I showed this on a other forum and they said I did it wrong I corrected it but they really didn't explain what was wrong with it.

    here is my code
    Code:
      
          #include<stdio.h>
           
          int main()
          {
    
          char userinput[256];
    
          printf("Enter a string:");
          fgets(userinput,sizeof userinput,stdin);
          printf("&#37;s",userinput);
    
          return 0;
          }
    And here is the corrected one can someone please explain why I flush stdout and put a if there

    Code:
    #include<stdio.h>
    
    int main ( void )
    {
      char userinput[256];
        
      printf ( "Enter a string: " );
      fflush ( stdout );
    
      if ( fgets ( userinput, sizeof userinput, stdin ) != NULL )
        printf ( "%s", userinput );
        
      return 0;
    }
    Last edited by twitch; 06-08-2007 at 10:50 PM.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    The flush is done because stdout is line buffered by default, and there is no guarentee that the prompt message will be sent to the user before you try to read a line because you didn't append a '\n' to what was printed.

    The if statement is guarenteeing that fgets() worked. If it returned NULL, then something wrong happened. You should not treat the buffer as if it has a string from the user until you find out what happened.

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    To be on a saver side and for the neatness thye fflush(stdout) is been used. But the return values of fgets should be checked ways.

    ssharish2005

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets not working after fgetc
    By 1978Corvette in forum C Programming
    Replies: 3
    Last Post: 01-22-2006, 06:33 PM
  2. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  3. problem with fgets
    By Smoot in forum C Programming
    Replies: 4
    Last Post: 12-07-2003, 03:35 AM
  4. fgets crashing my program
    By EvBladeRunnervE in forum C++ Programming
    Replies: 7
    Last Post: 08-11-2003, 12:08 PM
  5. help with fgets
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-17-2001, 08:18 PM