stringvisual-c++newlineline-breaksmanaged-c++

Add a new line using String^ in C++


I'm writing a program where you can enter text and output a text file with that text.

I have this:

int _tmain(int argc, _TCHAR* argv[])
{
    String^ fileName = "registry.txt";
    String^ out;

    StreamWriter^ sw = gcnew StreamWriter(fileName);

    out = "hi";
    out = out + "\n how you doing?";

    sw->WriteLine(out);

    sw->Close();
}

Basically I want this:

hi
how you doing?

But what I get is this:

hi how you doing?

How can I fix it?


Solution

  • Use static data member Environment::NewLine

    For example

    out = out + Environment::NewLine + " how you doing?";
    

    Or you can explicitly specfy escape control symbol '\r' along with '\n' used in Windows to separate lines.

    out = out + "\r\n how you doing?";
    

    Here is an example of using the both methods

    #include "stdafx.h"
    
    using namespace System;
    using namespace System::IO;
    
    int main(array<System::String ^> ^args)
    {
        String ^fileName( "Data.txt" );
        String^ out;
    
        StreamWriter^ sw = gcnew StreamWriter( fileName );
    
        out = "hi";
        out = out + "\r\n how you doing?";
    
        sw->WriteLine(out);
    
        out = "hi";
        out = out + Environment::NewLine + " how you doing?";
    
        sw->WriteLine(out);
    
        sw->Close();
    
        return 0;
    }
    

    The output is

    hi
     how you doing?
    hi
     how you doing?