简体   繁体   中英

wrong format when saving to file

I am trying to save a String Builder to a file but it doesn't make new line. the output should look like 在此处输入图片说明

output without new line 在此处输入图片说明

class Program
{
    static public void justify(List<string> words, int width)
    {
        //some code to build the arrays
        int ii = 0, jj;
        StringBuilder builder = new StringBuilder();
        do
        {
            jj = result[ii];

            for(int k = ii; k < jj; k++)
            {
                builder.Append(words[k] + " ");
            }

            builder.Append("\n");
            ii = jj;
        }
        while(jj < words.Count);
        Console.WriteLine(builder.ToString());
        StreamWriter file = new StreamWriter("output.txt");
        file.Write(builder.ToString());
        file.Close();
    }

    static void Main(string[] args)
    {
        string file_extention, file1;
        file1 = Console.ReadLine();
        file_extention = "C:\\Users\\sayed\\Desktop\\" + file1 + ".txt";
        string text = System.IO.File.ReadAllText(@file_extention);
        result = text.Split(' ').ToList();
        justify(result, 10);
    }
}

That's because the you should use \\r\\n for new lines in Windows. \\n is Unix. You should use

builder.AppendLine();

which does this automatically. More precisely, AppendLine() appends a \\r\\n on non-Unix platforms and a string \\n on Unix platforms.

Note that your file does indeed contain the \\n which some editors do interpret as line breaks even on Windows. Notepad, for instance, does not.

Replace

builder.Append("\n");

with

builder.Append(Environment.NewLine);

Then open your file with notepad++ instead of window's default text editor.

I believe your \\n characters are being ignored by notepad and so they aren't rendering. On Windows machines, it expects a \\r\\n to render a newline and Environment.NewLine will make sure you get the right one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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