0

How would I get a code like this to keep everything formatted together?

Console.WriteLine("{0}\t{1}", name[j], score[j]);

When some of the names are longer and messes up the formatting so it outputs something like

Henrichson      100
Mike    80

Is there a way to make it so the scores are always in the same column?

user2781666
  • 167
  • 1
  • 2
  • 11
  • 1
    Based on the maximum length of your name create a string with quantity of spaces to "make" a column. Using \t is not going to work ever. – Maximiliano Rios Dec 01 '13 at 00:42
  • Take a look at this question and the answers there: http://stackoverflow.com/questions/856845/how-to-best-way-to-draw-table-in-console-app-c – mynkow Dec 01 '13 at 00:45
  • @Maximiliano Rios Is it possible to adjust the column length based on the highest character count of a name array? – user2781666 Dec 01 '13 at 00:57
  • My guess is it would be a best idea. People gave you a couple of ideas already based on that. I would calculate first the column width or I would set in case it's a fixed field – Maximiliano Rios Dec 01 '13 at 03:25

2 Answers2

2

You can use String.PadRight() to make fixed column widths.

const int columnWidth = 15;

Console.WriteLine("{0} {1}", name[j].PadRight(columnWidth), score[j]);

columnWidth represents the target number of characters you want in the string. If the input string is less than the target, it will append spaces (by default).

Alternatively, you can make use of the built in format specifier options by adding a negative integer representing columnWidth as an argument in the specifer.

Console.WriteLine("{0,-15} {1}", name[j], score[j]);
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
  • Thanks for that, quick question though, since columnWidth is a constant should it be in all caps? I was wondering if it was just a requirement of my teacher's or a real thing – user2781666 Dec 01 '13 at 00:55
  • `columnWidth` doesn't have to be a constant, It's just good practice for data that won't be changed. As for capitalization, that's just a naming convention and I normally would use all caps with underscores delimiting words, but for the context of this answer it's not really needed. – Austin Brunkhorst Dec 01 '13 at 01:07
1

Use padding with proper max length, so rest will be filled with spaces:

Console.WriteLine("{0,-18}\t{1}", name[j], score[j]);
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58