-2

So I have a two-dimensional array and I want to write all data to a text-file. But I want them to appear in columns in the text-file.

(I haven't declared them like this in my code, but I think this is what the array would look like written out):

myArray = [{Jamie, 5}, {Susan, 7}, {Robert, 2}, {Sam, 9}];

I want in the text-file it to look like this:

Jamie    5
Susan    7
Robert   2
Sam      9

I have looked at other answers such as How to write contents of an array to a text file? C# and Format a string into columns but I feel like they are only answering half of my question, and I don't understand them either.

What I have so far is:

using (StreamWriter sw = new StreamWriter(@"../../test.txt", false))
{
   foreach ()
   {
   }
}

I'm not sure what I am supposed to have in foreach().

How do I do this?

Anonym
  • 9
  • 1
  • Is it homework? *Can anyone help me?* -> Yes, they can, but see [this](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). *How do I do this?* - you have to decide, and give it a go; we're here to help you sort out problems you're having with implementing your design you came up with, not to come up with the whole design and implementation for you – Caius Jard Oct 22 '20 at 07:57
  • Take a look at this method: https://learn.microsoft.com/de-de/dotnet/api/system.io.streamwriter.writeline?view=netcore-3.1 and try to write things. You'll see how things are working. – user743414 Oct 22 '20 at 07:57
  • In `foreach` you have to iterate rows and output them. Perhaps you will need an inner loop for cells of that row. Perhaps you need two of such double-loops: one to calculate something used for formatting and another to actually perform formatted output. – Sinatr Oct 22 '20 at 08:01
  • A multidimensional array seems to be the wrong solution here, the only way you could make it work with ints and strings is if it was of type object. The second problem you have is padding anything in a file. We have a special file type for that, like CSV, and special readers to read them. – TheGeneral Oct 22 '20 at 08:31

1 Answers1

0

One easy way is to:

  1. Iterate all strings you need to output and store the length of the longest one.
  2. Iterate again all items; using two nested loop (rows and columns) seems like a good idea.
  3. Write each item you iterate in step 2 padded to the right with enough whitespaces to account for column spacing and the longest length of step 1. string.PadRight seems like a good option.

You are done.

Of couse yo can get fancier and store the longest length of each column and then pad each column with it's specific length...

InBetween
  • 32,319
  • 3
  • 50
  • 90