从文件中添加数字

时间:2013-05-01 08:13:33

标签: c#

我想要做的是从文件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 个答案:

答案 0 :(得分: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来检查你的数字是否真的是整数(如果无法将字符串转换为整数值,则Parse将引发异常)。

此外,我已使用using statement打开文件,并确保关闭和处理StreamReader的正确方法