简体   繁体   English

新线从哪里来。 从文件读取并放入字符串。 然后输出到控制台

[英]Where does the new line come from. Read from a file and put in a string. Then output to the console

I want to understand why there is a newline when console.writeline outputs this text which is from a string variable. 我想了解当console.writeline输出来自字符串变量的文本时为什么会有换行符。 "Now is the time for all good people". “现在是所有好人的时候了”。

    String filename = @"C:\data\chars.txt";

        TextWriter aText = File.AppendText(filename);
        String lineToWrite = "Now is the time for all good people";
        aText.WriteLine(lineToWrite);
        aText.Close();
        StreamReader aStream = new StreamReader(filename);
        string words = "";
        char letter;
        while (aStream.Peek() != -1)
        {
            letter = Convert.ToChar(aStream.Read());
            Console.WriteLine(letter);
            words += letter;
        }
        aStream.Close();
        Console.WriteLine(words);

        Console.ReadKey();

Console writeline is only called once, but the terminal screen show the string line by line, when there are 3 lines in the file, so if I run it again there will be 4 lines on the screen, each on there own line, where does the newline character come from? 控制台writeline仅被调用一次,但是终端屏幕逐行显示字符串,当文件中有3行时,因此如果再次运行它,屏幕上将有4行,每行有一行,在哪里换行符来自哪里?

aText.WriteLine(lineToWrite);

You are appending to the file using WriteLine method. 您正在使用WriteLine方法追加到文件。 This appends a newline character at the end of each line. 这将在每行末尾添加一个换行符。 When you are printing it to the console this newline character gets printed. 当您将其打印到控制台时,将打印此换行符。 The word at the end of each line contains the newline character and it gets printed. 每行末尾的单词包含换行符并被打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM