2016-07-26 52 views
0

我有一個包含多個數字的.txt文件,我希望它讀取文件並輸出數字。但是當它讀取文件時,它會輸出System.String []而不是數字。任何幫助,將不勝感激。從.txt文件讀取輸出System.String []而不是預期的結果c#

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] unsorted = System.IO.File.ReadAllLines(@"\University\AlgRetake\Files\WS1_AF.txt"); 
     //Grabs the .txt file and reads line by line 

     System.Console.WriteLine("Unsorted: "); 
     foreach (string line in unsorted) 
     { 
      Console.WriteLine(unsorted); 
     } 
     //outputs the unsorted array 


     Console.WriteLine("Press any key to exit!"); 
     System.Console.ReadKey(); 

    } 
} 
+0

你想要寫的是未排序,而不是實際的行更有效輪到你了。由於數組(甚至是String數組)沒有內置的很好的toString實現,它只是打印類型。將它改爲'Console.WriteLine(line)'應該可以解決這個問題。 –

回答

4

在你的foreach循環,你應該有Console.WriteLine(line);

否則,你正在編寫強制轉換爲字符串到控制檯的字符串數組對象。

+0

非常感謝:) –

1

你非常接近 - 你需要輸出LINE。 即 - LINE是每個數組條目。

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] unsorted = System.IO.File.ReadAllLines(@"\University\AlgRetake\Files\WS1_AF.txt"); 
     //Grabs the .txt file and reads line by line 

     System.Console.WriteLine("Unsorted: "); 
     foreach (string line in unsorted) 
     { 
      ****Console.WriteLine(line);**** 
     } 
     //outputs the unsorted array 


     Console.WriteLine("Press any key to exit!"); 
     System.Console.ReadKey(); 

    } 
} 
+1

只是一個星號:星號,雖然他們呼籲關注代碼更改,但也使代碼無法編譯。如果有人試圖直接使用您的代碼,那麼使用評論來發布更改可能更有意義。無論如何。 – adv12

+0

足夠公平。再也不。 我試圖加粗它;) – AntDC

0

行現有的答案
但這是沒有開銷的閱讀的String []無序

using (StreamReader sr = new StreamReader(path)) 
{ 
    while (sr.Peek() >= 0) 
    { 
     Console.WriteLine(sr.ReadLine()); 
    } 
} 
+0

可能值得解釋爲什麼這樣更有效率,以及在什麼情況下效率的差異很重要。 –