将数组值写入列和行中的文件

时间:2016-09-07 17:30:14

标签: c# formatting

我目前仍在尝试将输入到我的数组中的值输入到rows = 30cols = 5中的文件中。从我的代码中,它目前正在直接编写它们。我该如何解决这个问题?

CODE:

static void PrintReport()
{
  fileOut.WriteLine();
  fileOut.WriteLine("Score       Score       Score       Score       Score");
  fileOut.WriteLine("-----       -----       -----       -----       -----");
  fileOut.WriteLine("");

}

static void InputValues()
{
  int n = 0, row, col;
  int numOfRows, numOfCols;
  string[] words;

  words = fileIn.ReadLine().Split(',');
  numOfRows = Int32.Parse(words[0]);
  numOfCols = Int32.Parse(words[1]);
  numOfValues = numOfRows * numOfCols;
  valueArray = new double[numOfValues + 1];
  for (row = 1; row <= numOfRows; row++)
  {
    words = fileIn.ReadLine().Split(',');
    for (col = 1; col <= numOfCols; col++)
    {
      //n = numOfCols*(row-1) + col; 
      n++;
      valueArray[n] = Double.Parse(words[col - 1]);
    }
  }
}

期望的输出:

desired output

2 个答案:

答案 0 :(得分:0)

如果您正在寻找格式,下面是一个片段。如果总是有30x5,它就可以工作。否则你需要改变逻辑。 $“”语法仅适用于C#6.0。您需要在较低版本中使用string.Format。 \ t是间距。您也可以通过增加5来调整。

void Print(double[] valueArray)
    {
        for(int row = 0; row <150; row+=5)
        {
            Console.WriteLine($"{valueArray[row],5:N2}\t{valueArray[row + 1],5:N2}\t{valueArray[row + 2],5:N2}\t{valueArray[row + 3],5:N2}\t{valueArray[row + 4],5:N2}\t");
        }
    }

答案 1 :(得分:0)

static void PrintReport()
{
  int count;
  fileOut.WriteLine();
  fileOut.WriteLine("Score       Score       Score       Score       Score");
  fileOut.WriteLine("-----       -----       -----       -----       -----");
  for (int row = 1; row <= numOfRows; row++)
  {
    for (int col = 1; col <= numOfCols; col++)
    {
      count = row + numOfRows * (col - 1);
      if (count <= numOfValues)
        fileOut.Write("{0,5:N2}       ", valueArray[count]);
    }
    fileOut.WriteLine();

  }
}

这解决了我的问题