我正在处理我正在处理的控制台应用程序的输出数据中的换行符时遇到问题。下面的简化示例是将outDataString写入out.txt而不使用换行符。在这种情况下,有关如何在out.txt中实现换行的任何想法吗?
FileStream ostrm;
StreamWriter writer;
string outDataString = "Hi, this is the out data.\nWith a few\n line breaks.";
ostrm = new FileStream("out.txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(outDataString);
Console.SetOut(writer);
Console.write(outDataString);
感谢。
答案 0 :(得分:5)
string outDataString = string.Format(
"Hi, this is the out data.{0}With a few{0} line breaks.",
Environment.NewLine);
答案 1 :(得分:1)
我认为原始代码应该是:
var ostrm = new FileStream("out.txt", FileMode.OpenOrCreate, FileAccess.Write);
var writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.Write(outDataString);
在之前的Windows和DOS中,您需要输入\r\n
来更改该行。实际上,这可以追溯到CP / M.
你可以写:
string outDataString = "Hi, this is the out data.\r\nWith a few\r\n line breaks.";
如果你真的不想写一个包含多行的字符串文字,最好用StreamWriter.WriteLine分别写每一行,例如:
Console.WriteLine(firstLine);
Console.WriteLine(secondLine);
甚至
var lines=new[]{"My First Line","My Second Line"};
foreach(var line in lines)
Console.WriteLine(secondLine);
答案 2 :(得分:1)
FileStream ostrm;
StreamWriter writer;
string outDataString = String.Format("Hi, this is the out data.{0}With a few{0} line breaks.", System.Environment.NewLine);
ostrm = new FileStream("out.txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(outDataString);
Console.SetOut(writer);
答案 3 :(得分:0)
这是在运行什么平台?在Windows上,您需要回车符和换行符来表示换行符,因此您需要将\ n替换为\ r \ n
理想情况下,您应该使用Environment.NewLine,而不是以这种方式在文字中嵌入换行符,这会使您的代码更有可能跨平台工作。