Search code examples
c#conditional-statementsstreamreaderpeek

Creating lines of 152 characters and adjusting line endings at ends of words


I am trying to write a little utility class for myself to do some formatting of text so that each line is as close as possible to 152 characters in length. I have written this code:

StreamReader sr = new StreamReader("C:\\Users\\Owner\\Videos\\XSplit\\Luke11\\Luke11fromweb.txt");
StreamWriter sw = new StreamWriter("C:\\Users\\Owner\\Videos\\XSplit\\Luke11\\Luke11raw.txt");
int count = 152;
char chunk;
do
{
    for (int i = 0; i < count; i++)
    {
        chunk = (char)sr.Read();
        sw.Write(chunk);
    }

    while (Char.IsWhiteSpace((char)sr.Peek()) == false && (char)sr.Peek() > -1)
    {
        chunk = (char)sr.Read();
        sw.Write(chunk);
    }
    sw.WriteLine();
} while (sr.Peek() >= 0);

sr.Close();
sw.Close();

The for statement works fine. It reads and writes 152 characters without flaw. However, there is no guarantee that 152 characters will fall at the end of a word. So I wrote the nested while statement to check if the next character is a space, and if not, to read and write that character. The inner while statement is supposed to stop when it sees that the next character is a space, and then write in the line end statement.

After the reader and writer have gone through the entire document, I close them both and should have a new document where all the lines are approximately 152 characters long and end at the end of a word.

Obviously this isn't working as I anticipated and that is the reason for my question. Since the for statement works, there is something wrong in my nested while statement (perhaps the condition?) and I am not exiting the program without errors.

Any advice would be appreciated. Thanks in advance.


Solution

  • Your end of file test is incorrect

    while (Char.IsWhiteSpace((char)sr.Peek()) == false && (char)sr.Peek() > -1)
    

    you mean

    while (Char.IsWhiteSpace((char)sr.Peek()) == false && sr.Peek() > -1)
    

    as per docs

    The Peek method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a Char type.

    Note before casting