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?
Im a beginner to c, but here is something that should get rid of the '\n' after the strcat:
yourstring[strlen(yourstri ng) - 1] = '\0';
yourstring[strlen(yourstri
That code is not a good idea. check the C-FAQ on reasons why
Regards
Friedrich
Regards
Friedrich
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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.
assume
char *string = "xyz\n"; than this will work
char *pc = NULL;
if ((pc = strchr(string, '\n')) != NULL)
*pc = '\0';
Regard
Friedrich