Guilherme Almeida
Guilherme Almeida

Reputation: 89

C# TextWriter adds new line for no reason

Hello fellow StackOverflow users.

The Problem

I have a simple C# code, where I have method that takes both an TextReader (reader) and an TextWriter (writer) as arguments.

Everytime I run writer.Write("\n") it jumpts 2 lines and writer.Write(" ") it adds an space and jumps 1 line. How can I prevent it from adding those new lines?

I am passing, respectively, Console.In and Console.Out as reader and writer.

The Code

public Matriz(TextReader reader, TextWriter writer) {
    int rows, columns;
    decimal[,] _map;

    ... reading rows number and columns number ...

    _map = new decimal[rows, columns];

    for (int i = 0; i < rows; ++i) {
        writer.Write ("\n"); // adds 2 lines
        for (int j = 0; j < columns; ++j) {
            writer.Write (""); // adds one line
            _map [i, j] = Convert.ToDecimal (reader.ReadLine ());
        }
    }

    this.map = _map;
}

Upvotes: -1

Views: 230

Answers (2)

Guilherme Almeida
Guilherme Almeida

Reputation: 89

The Solution

Dumb me! The problem is actually reader.ReadLine. When it gets called, it reads and adds a new line. Replacing it with reader.Read worked from me.

Upvotes: 0

Sami
Sami

Reputation: 3800

writer.Write(Environment.NewLine);

This might fix your problem. If it doesn't let me know. Thanks

Upvotes: 0

Related Questions