1

Maybe it's a very stupid question (I'm really noob with writing/reading/manipulate files) but I tried different method (found online and here on the site) but nothing worked :/ I have my matrix that is written in a file, and between each element of the matrix, there is a " , " like divider. I want " , " between every element but not at the end of the rows, so I opened again the file and tried to delete last char from each rows, but my code don't work!

//writing on the file
         using (TextWriter tw = new StreamWriter("PATH"))
         {
             for (int i = 0; i < colonne; i++)
             {
                 for (int y = 0; y < righe; y++)
                 {
                     tw.Write(matrice[y, i]+","); 
                 }
                 tw.WriteLine();
             }
         }

         using (FileStream fs = File.OpenWrite("PATH"))
         {
             fs.SetLength(fs.Length - 1);
             fs.Close();
         }

Thank you!

Denis Biondic
  • 7,943
  • 5
  • 48
  • 79
JEricaM
  • 794
  • 2
  • 15
  • 37
  • 2
    WriteLine is equivalent to `Write("\r\n")`. So the last three characters are `,\r\n`. You are removing the `\n`. – Mitch Jul 12 '15 at 16:28

1 Answers1

5

How about you simply do not output the ',' if last element:

for (int i = 0; i < colonne; i++)
{
    for (int y = 0; y < righe; y++)
    {
        tw.Write(matrice[y, i]); 

        if (y < righe - 1)
            tw.Write(",");
    }

    tw.WriteLine();
}
Denis Biondic
  • 7,943
  • 5
  • 48
  • 79
  • 2
    You could also write the comma before the item: `if (y != 0) { Write(","); } Write(matrice[y,I]);` – Mitch Jul 12 '15 at 16:31
  • Yeah, I would say that is even nicer – Denis Biondic Jul 12 '15 at 16:31
  • Before or after is kinda just preference but this is the right answer – Zach Jul 12 '15 at 16:35
  • 1
    You could also use a ternary statement: `tw.Write(matrice[y, i]+(y < (righe - 1) ? "," : ""));` Whether that's still "readable" just depends on who you ask. If you prefer to prepend the comma, then: `tw.Write((y == 0 ? "" : ",") + matrice[y, i]);` – Idle_Mind Jul 13 '15 at 00:50