2013-05-01 30 views
1

什么,我想要做的就是从text.txt文件读取的数字,它们加起来 该文件包含对自己行从文件中添加数字

86 
97 
144 
26 

所有。我很为难:L

这是我的代码:

namespace CH13EX1 
{ 
    class CH13EX1 
    { 
     static void Main(string[] args) 
     { 
      // opens the file 
      StreamReader inFile; 
      // tests to make sure the file exsits 
      if (File.Exists("text.txt")) 
      { 
       // declrations 
       string inValue; 
       int total; 
       int number; 
       // makes infile the file 
       inFile = new StreamReader("text.txt"); 
       // loop to real the files 
       while ((inValue = inFile.ReadLine()) != null) 
       { 
        number = int.Parse(inValue); 
        Console.WriteLine("{0}", number); 

       } 
      } 
     } 
    } 
} 
+1

大时,它的工作? – Thomas 2013-05-01 08:16:08

+0

你难以接受哪行代码? – 2013-05-01 08:16:09

+6

这里有很多专家可以给你答案,但是我觉得从长远来看,这对你无能为力。看起来你已经完成了所有困难的部分。你究竟在为什么而挣扎? – 2013-05-01 08:16:09

回答

3

到现有代码的最小变化是

int total = 0; 
using(inFile = new StreamReader("text.txt")) 
{ 
    while ((inValue = inFile.ReadLine()) != null) 
    { 
     if(Int32.TryParse(inValue, out number)) 
     { 
      total += number; 
      Console.WriteLine("{0}", number); 
     } 
     else 
      Console.WriteLine("{0} - not a number", inValue); 
    } 
} 
Console.WriteLine("The sum is {0}", total); 

当然,从文件中读取的值应添加到该变量保存单行上的值的运行总数,但我添加了more secure way来检查您的数字是否真的是整数(如果无法将字符串转换为整数值,则解析会引发异常)。

而且我已经使用了using statement打开该文件,并确保以正确的方式关闭和处置的StreamReader

+0

Ty,谢谢解决了我的问题,并且我很感激额外的信息:D – user2338717 2013-05-01 08:28:46

+0

也可以通过使用简单的'File.ReadLines'或'File.ReadAllLines'来避免任何'Stream'内容。 – SimpleVar 2013-05-01 09:04:04