Link to home
Start Free TrialLog in
Avatar of showbix
showbix

asked on

Remove "\n"

After using strcat(), I discover that my string is padded with "\n". How do I remove "\n" in my string?



Avatar of F. Dominicus
F. Dominicus
Flag of Germany image


assume
char *string = "xyz\n"; than this will work
char *pc = NULL;
  if ((pc = strchr(string, '\n')) != NULL)
    *pc = '\0';
 

Regard
Friedrich
Avatar of HelpMeImStupid
HelpMeImStupid

Im a beginner to c, but here is something that should get rid of the '\n' after the strcat:
yourstring[strlen(yourstring) - 1] = '\0';
That code is not a good idea. check the C-FAQ on reasons why

Regards
Friedrich
ASKER CERTIFIED SOLUTION
Avatar of HelpMeImStupid
HelpMeImStupid

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Example why the code can fail miserably.

Assume you have used fgets
you have read
abcdef\n (this is the end of the file

but what is strlen? strlen runs happily over the memory and stops if if find a '\0' character. Well your buffer is obviously just 7 elemetns larga and no '\0' anywhere.

strlen just works if you deal with proper strings a string read in with fgets does not have to be proper.

Regards
Friedrich

I was figuring that strcat would make it a proper string since it null terminates and the strings you pass to it should be null terminated. So it should work in that case.
str[strlen(str)-1]=0; can be even more catastrophic if str is "".  It will access str[-1] and may mess up unexpected stuff.