tags:

views:

178

answers:

3

Hi,

in a C++ program, there is a point when it reads a string like:

"NONAME_1_1\r"

the \r is causing me trouble. I guess it prints or adds something like "^M". Is it right? Anyway it casues me problem, and I want to get rid of it.

I can not modify the input. I wonder how could I at this point, using C++, and in the easiest way, to remove \r for this string.

I know how to do it on bash but no clue on C++.

Thanks.

A: 

That depends on how you are holding it in memory:

  1. If it's in a std::string, just check the last byte and remove it if it's a '\r'.
  2. If it's in a const char*, you can use strncpy to copy the string into another char array, conditionally grabbing the last byte.
  3. If, by "I can not modify the input," you simply mean that you can't touch the source file, then you may have the option to read it into a char array and replace any trailing '\r' with '\0'.
Marcelo Cantos
i see. then is it that easy just like detecting \r ? could you tell me how would you then do it? thanks a lot
Werner
@Werner, I don't know how you are representing the input. Some sample code in your question would help.
Marcelo Cantos
+1  A: 
Charles Bailey
just a last question, when comparing strings character to character, I thought that "\r" would take two chars, but not, it is just one. how would i use a conditional ? if char[4]==`\r' ???
Werner
@Werner: Backslash introduces and escape sequence. `\r` is a carriage return, ASCII code decimal 13/ hex 0D, `^M`, etc. In single quotes it is a single character constant; in double quotes it would be a string literal composed of two characters: ASCII 13 and a terminating null.
Charles Bailey
A: 

This is a common problem when reading lines from files after moving them between unix and windows.

  • Unix variants use "\n" (line feed) to terminate lines.
  • Windows uses "\r\n" (carriage return, line feed) to terminate lines.

You can run the "dos2unix" or "unix2dos" to convert lines in a file.

Stephen
i know that, but the problem has to be solved on the code
Werner
Then use Charles Bailey's solution.
Stephen