Niclas W
Niclas W

Reputation: 21

Console window cuts of text in sequence

I am just beggining coding, and cant find a solution in my textbook, as Im studying from home to later validate in a noob programme course, I dont have a teacher to ask..

C#

Console.Write("write a interger between 1 and 100: ");
string anvS = Console.ReadLine();
int anvI;
if (int.TryParse(anvS, out anvI))
{
  if (anvI < 100)
  {
    while (anvI <= 100)
    {
      Console.Write(anvI++ + " ");
    }
    Console.ReadKey();
  }
  else
  {}
}
else
{}

The problem:

enter image description here

As you can see it cuts of the format in the upper right.

Also, as im somewhat a newbie, is there a easy fix that not to complicated, and whats the more advanced fix?

Upvotes: 1

Views: 113

Answers (2)

Gediminas Masaitis
Gediminas Masaitis

Reputation: 3212

The Windows console has two widths, measured in characters. One is the buffer width - how many available characters you have in a single line. The other is the window width - how wide your actual console window is. If your buffer width is bigger than your window width, your console will have a horizontal scrollbar. You can see and set them if you right-click the console title bar and click Properties.

The console doesn't care about words, it just wraps at exactly that many characters, default being 80. To prevent this, you would need to word-wrap manually - format your output so that it doesn't go over whatever your console width is set to. You can get (and set) the widths using Console.BufferWidth and Console.WindowWidth respectively.

Here is one way to do what you want:

Console.Write("Write an interger between 1 and 100:");
string inputS = Console.ReadLine();
int inputI;
if (int.TryParse(inputS, out inputI) && inputI < 100)
{
    var lineBuilder = new StringBuilder();
    while (inputI <= 100)
    {
        var numStr = inputI + " ";
        if (lineBuilder.Length + numStr.Length > Console.WindowWidth)
        {
            Console.WriteLine(lineBuilder.ToString());
            lineBuilder.Clear();
        }
        lineBuilder.Append(numStr);
        inputI++;
    }
    if (lineBuilder.Length > 0)
    {
        Console.WriteLine(lineBuilder.ToString());
    }
    Console.ReadKey();
}

Upvotes: 0

benPearce
benPearce

Reputation: 38353

This is how the Windows console works, you can change the size of the console through the Console class. You could also write each number on a new line, or collect your numbers in an array and write them out in a formatted table at the end.

List<int> listOfNumbers = new List<int>();

Replace your Console.Write line with listOfNumbers.Add(anvI++);

The write your output at the end:

for (int i = 0; i < 100; i += 5)
{
    Console.WriteLine(string.Join(" ", listOfNumbers.Skip(i).Take(5)));
}

Upvotes: 2

Related Questions