Mac C printf variable making new line using fgets

Cabbit

macrumors 68020
Original poster
Jan 30, 2006
2,129
1
Scotland
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
 

longofest

Editor emeritus
Jul 10, 2003
2,817
1,304
Falls Church, VA
...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.
 

Cabbit

macrumors 68020
Original poster
Jan 30, 2006
2,129
1
Scotland
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.