【问题标题】:Add a new line using String^ in C++在 C++ 中使用 String^ 添加新行
【发布时间】:2014-05-05 16:38:33
【问题描述】:

我正在编写一个程序,您可以在其中输入文本并输出带有该文本的文本文件。

我有这个:

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?

我该如何解决?

【问题讨论】:

标签: string visual-c++ newline line-breaks managed-c++


【解决方案1】:

使用静态数据成员Environment::NewLine

例如

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

或者您可以明确指定转义控制符号“\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?

【讨论】:

    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多