Arielle
Arielle

Reputation: 1251

Convert a string's UNIX line endings to DOS line endings

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?

Upvotes: 0

Views: 3925

Answers (3)

James Kanze
James Kanze

Reputation: 153929

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'.

Upvotes: 4

Logicrat
Logicrat

Reputation: 4468

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

Upvotes: 1

George Hilliard
George Hilliard

Reputation: 15952

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.

Upvotes: 2

Related Questions