0

I'd like to convert a string's UNIX line endings to DOS ones, because my program communicates with a server running on a Linux-based operating system. I've tried using std::replace like that:

std::string str = readfromserver(); 
std::replace(str.begin(), str.end(), "\n", "\r\n");

but I got the following compiler error:

error C2782: 'void std::replace(_FwdIt,_FwdIt,const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous

Could anyone tell me what am I doing wrong or suggest me a different way of line ending conversion?

Arielle
  • 1,241
  • 2
  • 11
  • 14

3 Answers3

4

What are you trying to do, exactly? Internally, regardless of the system, line endings are '\n'. If you're on a Windows system, they will be converted correctly in std::ifstream and std::ofstream, you don't have to worry about it (provided you open the files in text mode). And an std::ifstream will read a file written under Unix without problems. The only time you might have to pay attention to this issue is when writing on Windows and reading on Unix; then you will probably find an extra '\r' immediately in front of the '\n'. Normally, this is not a problem either, because the '\r' count as legal white space, and you want to ignore trailing white space anyway.

Within a C++ program, you should never see the '\r'.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

Adapted from this answer, Boost has an excellent string manipulation library. And because it's Boost, it's pretty much guaranteed to be as fast as possible.

Use boost::replace_all:

std::string str = readfromserver();
boost::replace_all(str, "\n", "\r\n");

And if you need to go the other way (removing \rs), you could just use an standard library algorithm such as remove_if and a lambda.

Community
  • 1
  • 1
George Hilliard
  • 15,402
  • 9
  • 58
  • 96
0

I'd replace "\n" with something that does not itself contain the "\n" escape sequence, such as "\x0x0d\0x0a".

Logicrat
  • 4,438
  • 16
  • 22