C printf variable making new line using fgets

Discussion in 'Mac Programming' started by Cabbit, Jul 25, 2010.

  1. Cabbit macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #1
    Code:
    	// Get username
    	printf("What was your name again? ");
    	
    	// Get username using fgets, this is how to do it without a security error
        fgets(name, 15, stdin);
    	// End get username
    	
    	// The user hears someone calling their name, using variable called name
    	printf("Mysterious Voice %s %s \n", name, name);
    
    My expected output is "Mysterious Voice name name", my actual output is "Mysterious Voice name
    name

    "

    Anyone know why and how to fix it. name is a char
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    The newline is coming from the fgets. You can strip it after you read it, that should take care of it.

    -Lee
     
  3. longofest Editor emeritus

    longofest

    Joined:
    Jul 10, 2003
    Location:
    Falls Church, VA
    #3
    ...more precisely, it's coming from the user input. fgets() gives you everything the user inputs up to and including the \n. like lee said, strip it, and you're golden.
     
  4. Cabbit thread starter macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #4
    i fixed it as you suggested using
    Code:
    // Remove \n from name
    	len = strlen(name);
    	if( name[len-1] == '\n' )
    		name[len-1] = 0;
    
    I was using gets() before which did not have the same problem.
     
  5. ianray macrumors 6502

    Joined:
    Jun 22, 2010
    Location:
    @
    #5
    Good move though :)

    fgets() is safer than gets() because the former includes a buffer length.
     

Share This Page