2014-03-26 53 views
1

我有點新的C++和這個網站,所以容忍我:)添加使用字符串^在C++中

我正在寫一個程序,您可以輸入文本和輸出文本文件中的新行與那個文本。

我現在是這樣的:

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(); 
} 

基本上我想是這樣的:

hi 
how you doing? 

,但我所得到的是這樣的:

hi how you doing? 

有什麼建議?

+2

這是管理C++。請使用適當的語言標籤。 – chris

+0

這是C++ - CLI嗎?如果是這樣,請標記爲。 – 0x499602D2

+0

可能重複的[我不能添加一個新行到c + +字符串](http://stackoverflow.com/questions/4128077/i-cant-add-a-new-line-to-c-string) – juanreyesv

回答

2

使用靜態數據成員Environment::NewLine

例如

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

或者你可以明確地specfy逃脫控制符號 '\ r' 在Windows中被用來分隔行 '\ n' 一起。

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

下面是使用兩種方法

的一例
#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; 
} 

輸出是

hi 
how you doing? 
hi 
how you doing? 
+0

謝謝你真的幫助了! – user3466458