Delete new line character in C

I'm trying to use getc(character) to take an element from a file and do something with it, but it seems like it should have '\n' to the end of the line.

How can I remove this so that when copying characters I don’t have a new line character appearing anywhere, which allows me to deal with printing new lines when I select?

+4
source share
7 answers

Hmm, wouldn't it help to use getc to fill the buffer and remove newlines and carriage returns?

+2
source
 . . . #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 am not a huge fan of dropping \ 0 characters in such lines. This does not work well when you start making i18n and the width of the characters is not fixed. UTF-8, for example, you can use from 1 to 4 bytes per " symbol".)

+6
source

To replace the entire new char string with spaces, use:

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

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

 char *pch = strstr(myStr, "\n"); if(pch != NULL) strncpy(pch, "\0", 1); 
+4
source

You can replace it with a null terminator.

Here is one (simple) way to do it from the head:

  mystr[ strlen(mystr) - 1 ] = '\0'; 
+2
source

Suppose buf is of type char and it contains the string value read from the file ...

  buf [strlen (buf) -1] = '\ 0';

This sets the second-last character of the buffer to nul ie '\ 0' to remove the newline character.

Edit: Since loz mentions a compiler error, I suspect const char * ... Can we see the code, please ...

+1
source

The following will do the trick

 line[strlen(line) - 1] = 0 
0
source

More full version:

 char* end = line + strlen(line) - 1 ; // end of line while( (end > line) && isspace(*end) ) end--; // right trim space *(end+1) = '\0'; // terminate string 

(Note: Entering a null char value in it causes the line readers to stop reading data at this point, but the memory size is the same. The characters to the right of '\ 0' still exist.

0
source

Source: https://habr.com/ru/post/1303395/


All Articles