string - 在 C++ 中使用 String^ 添加新行

标签 string visual-c++ newline line-breaks managed-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?

如何修复它?

最佳答案

使用静态数据成员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?

关于string - 在 C++ 中使用 String^ 添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675197/

相关文章:

javascript - javascript 如何解析带引号的 JSON 字符串

Java:字符串模式:如何为所有具有特殊字符的字母字符指定正则表达式

python - 字符串连接的变体?

c++ - vector 正在抛出 bad_alloc

c++ - 在我的文档中创建文件夹

python - TextArea 将所有换行符加倍

c - 为什么可以将字符串指针初始化为字符串文字,而不是数组?

c - 在 C 中的宏中重新定义标签

iOS UITextfield : Crashes on press of enter/return key

string - PostgreSQL 换行符