Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove new line character in C

Tags:

c

I am trying to use getc(character) to take an element from a file and do stuff with it, but it appears that it must have a '\n' before the end of a line is met.

How can I remove this so that when I copy the characters I don't have a new line character appearing anywhere - thus allowing me to deal with printing new lines when I choose?

like image 257
Biscuit128 Avatar asked Mar 07 '10 14:03

Biscuit128


3 Answers

.
.
.
#include <string.h>
.
. /* insert stuff here */
.
char* mystring = "THIS IS MY STRING\n"
char* deststring;
.
.
.
strncpy(deststring, mystring, strlen(mystring)-1);
.
.
.

(As an added note, I'm not a huge fan of dropping \0 characters in strings like that. It doesn't work well when you start doing i18n and the character width is not fixed. UTF-8, for example, can use anywhere from 1 to 4 bytes per "character".)

like image 130
JUST MY correct OPINION Avatar answered Oct 07 '22 15:10

JUST MY correct OPINION


To replace all new line char with spaces, use:

char *pch = strstr(myStr, "\n");
while(pch != NULL)
{
    strncpy(pch, " ", 1);
    pch = strstr(myStr, "\n");
}

To remove first occurrence of new line char in string, use:

char *pch = strstr(myStr, "\n");
if(pch != NULL)
  strncpy(pch, "\0", 1);
like image 26
Nitinkumar Ambekar Avatar answered Oct 07 '22 15:10

Nitinkumar Ambekar


Hmm, wouldn't help to use getc to fill a buffer and remove newline and carriage return characters?

like image 34
Gabriel Ščerbák Avatar answered Oct 07 '22 15:10

Gabriel Ščerbák