Search code examples
c#streamreader

How i count summary of numbers in a text file?


I did this code, but it doesnt give summary. Still I can get numbers of each row, but not summary...

using System;
using System.IO;
namespace Progaram
{
    class Count
    {
        static void Main()
        {

            using (StreamReader sr = new StreamReader("file.txt"))
            {

                string[] numbers = File.ReadAllLines("file.txt");


                int summary = 0;

                for (int i = 0; i < numbers.Length; i++)
                {

                    summary += numbers[i];

                    //Console.WriteLine(numbers[i]);
                }

                Console.WriteLine(summary);

                sr.ReadLine();
            }
        }
    }
}

Solution

  • Your current solution will not compile.
    You'll receive the following compilation error:

    Cannot convert type 'string' to 'int'.

    You'll want to convert the parsed string into an int.

    Also, you're using a StreamReader, and reading a single line after reading in all lines. You don't need the StreamReader in this case.

    using System;
    using System.IO;
    
    namespace Progaram
    {
        class Count
        {
            static void Main()
            {
                string[] numbers = File.ReadAllLines("file.txt");
    
                int summary = 0;
    
                for (int i = 0; i < numbers.Length; i++)
                {
                    summary += Convert.ToInt32(numbers[i]);
                }
    
                Console.WriteLine(summary);    
            }
        }
    }