tags:

views:

246

answers:

4

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 charachter appearing anywhere - thus allowing me to deal with printing new lines when I choose?

A: 

You could replace it with a null terminator.

Here is one (simple) way to do it off the top of my head:

 mystr[ strlen(mystr) - 1 ] = '\0';
Justin Ethier
shouldn't you verify that the char is a lf before nuking it?
lexu
Works fine until your employer decides to internationalize and your strings become UTF-8 encoded.
JUST MY correct OPINION
Right, but your solution has the same problem. Typically you would need to use a different set of functions other than the str* series in order to deal with unicode. For example, using wcscpy instead of strcpy for Win32 programming. In any case, it was just a quick example.
Justin Ethier
@lexu - Do you mean the code should check to see that the char being replaced is a newline? Yes, that would probably be a good idea. However, all of the solutions more or less assume that his code is doing that check already.
Justin Ethier
A: 

Supposing that buf is of type char and it holds the string value read in from the file...

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

That sets the second-last character of the buffer to nul i.e. '\0' in order to remove the new-line character.

Edit: Since loz mentioned a compiler error I suspect it's a const char * is used...Can we see the code please...

tommieb75
this gives an error saying passing arg 1 of strlen makes pointer from integer without a cast
loz
shouldn't you verify that the char is a lf before nuking it?
lexu
Well....the poster did not post code here....so it's difficult to say....
tommieb75
Works fine until your employer decides to internationalize and your strings become UTF-8 encoded.
JUST MY correct OPINION
Who downvoted this? We're shooting ourselves in the foot if loz did not post code...how are we supposed to know...
tommieb75
A: 
.
.
.
#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".)

JUST MY correct OPINION
+2  A: 

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

Gabriel Ščerbák
If he's using getc anyway, yeah it's probably smartest to just not copy the character into the buffer when doing that.
JUST MY correct OPINION