Remove  "\n"

showbix
showbix used Ask the Experts™
on
After using strcat(), I discover that my string is padded with "\n". How do I remove "\n" in my string?



Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
fridomCEO/Programmer

Commented:

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

Regard
Friedrich
Im a beginner to c, but here is something that should get rid of the '\n' after the strcat:
yourstring[strlen(yourstring) - 1] = '\0';
fridomCEO/Programmer

Commented:
That code is not a good idea. check the C-FAQ on reasons why

Regards
Friedrich
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Hi Friedrich, why wouldn't that code work to get rid of a newline character at the end of a string? Is it because the size of the string is changed when I set it equal to the null character? So would this be better:

int length;
length = strlen(yourstring);
yourstring[length-1] = '\0';
fridomCEO/Programmer

Commented:
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.

Commented:
str[strlen(str)-1]=0; can be even more catastrophic if str is "".  It will access str[-1] and may mess up unexpected stuff.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial