2015-05-19 53 views
0

我有以下程序,它只是將兩個矩陣從.txt文件讀入二維數組。我從開發人員命令提示符下運行它VS2012像第一張圖片兩個.txt文件的命令行參數

using System; 
 
using System.Collections.Generic; 
 
using System.Linq; 
 
using System.Text; 
 
using System.Threading.Tasks; 
 
using System.IO; 
 

 

 
namespace Assignment3 
 
{ 
 
    class Program 
 
    { 
 
     static void Main(string[] args) 
 
     { 
 

 
      int[,] matrix1 = new int[3, 3]; int[,] matrix2 = new int[3, 3]; int[,] matrix3 = new int[3, 3]; 
 
      int i = 0, j = 0, k = 0; 
 
      #region Reading Matrices From Files 
 
      
 
      string text = System.IO.File.ReadAllText(@"Matrix1.txt"); 
 
      
 
      
 
      foreach (var row in text.Split('\n')) 
 
      { 
 
       j = 0; 
 
       foreach (var col in row.Trim().Split(' ')) 
 
       { 
 
        matrix1[i, j] = int.Parse(col.Trim()); 
 
        j++; 
 
       } 
 
       i++; 
 
      } 
 
      Console.WriteLine("Execution Starts Here"); 
 
      Console.WriteLine("\nMatrix1 Has been read from file Matrix1.txt...\n"); 
 
      for (i = 0; i < 3; i++) 
 
      { 
 
       for (j = 0; j < 3; j++) 
 
       { 
 
        Console.Write(String.Format("{0}\t", matrix1[i,j])); 
 
       } 
 
       Console.WriteLine(); 
 
      } 
 

 
      
 
      string text2 = System.IO.File.ReadAllText(@"Matrix2.txt"); 
 
      i = 0; 
 

 
      foreach (var row in text2.Split('\n')) 
 
      { 
 
       j = 0; 
 
       foreach (var col in row.Trim().Split(' ')) 
 
       { 
 
        matrix2[i, j] = int.Parse(col.Trim()); 
 
        j++; 
 
       } 
 
       i++; 
 
      } 
 
      Console.WriteLine("\n\nMatrix2 Has been read from file Matrix2.txt...\n"); 
 
      for (i = 0; i < 3; i++) 
 
      { 
 
       for (j = 0; j < 3; j++) 
 
       { 
 
        Console.Write(String.Format("{0}\t", matrix2[i, j])); 
 
       } 
 
       Console.WriteLine(); 
 
      } 
 
      #endregion
enter image description here 這裏就是我打算做的是執行與文件名也是Program.exe文件(手段給予文件名執行時間),就像第二張圖片一樣。

enter image description here

我認爲這與喜歡的命令參數的數目一些事情。任何人都請幫助我。

+2

提示:'無效的主要(字串[] args)' – leppie

回答

1

Main方法的string[] args部分包含傳遞給應用程序的任何命令行參數。您可以通過args[0]args[1]訪問文件名。

編輯:我想補充,你可以在命令行參數使用時調試/通過查看屬性爲您的項目在運行Visual Studio中的應用(請在Solution Explorer中的項目,然後按Alt+Enter)和設置他們在Debug選項卡下的Command Line Arguments字段中。

編輯:針對在評論你的問題:那就是你有

string text = System.IO.File.ReadAllText(@"Matrix1.txt"); 

你硬編碼的文件名Matrix1.text。如果您希望能夠在運行時指定文件名,則有一個選項是將它們作爲命令行參數傳遞。這些命令行參數可以通過主方法中的args[]參數進行訪問。 args [0]包含第一個參數值,args [1]包含第二個參數值等等。所以,上面的線可以通過

string text = System.IO.File.ReadAllText(args[0]); 

值得注意的是,人們通常有一個驗證部分在Main方法確認用戶已通過參數的預期數量的首位,他們的更換預期類型。如果有任何例外情況,通常會顯示使用情況消息,然後退出應用程序。

+0

好了現在我有一點來說是有意義的,但如何分配這些ARGS [0]和args [1] .txt文件。根據這個代碼 –

+0

我已經更新了答案給你多一點細節。 – amcdermott

+0

真的很好,這就是我想要的。謝了哥們 –