Search code examples
c#variablesloopswhile-loopstreamreader

How to add up amount of data from an external file in C# (Stream Reader)


I'm new to this site, and pretty new to programming, at the moment I'm trying to display a count amount for the users names on my donation list, and then I also want to have a sum to work out the total amount of money the donation list contains, If someone could help me with creating a way to add up amount of donors on the donations.txt file that would be great help, I have no idea where to start, but so far this is my coding:

        string sName;
        double dAmount;
        string sTotalNames;
        double dAmountTotal;
        double dAmountAverage;

    using (StreamReader sr = new StreamReader("Donations.txt"))
    {
        while (sr.Peek() != -1)
        {
            sName = sr.ReadLine();
            Console.WriteLine(sName);

            dAmount = Convert.ToDouble(sr.ReadLine());
            Console.WriteLine(dAmount);
        }

        Console.WriteLine("Press any key to close");
        Console.ReadKey();
    }

Solution

  • Assuming everything else you have works correctly, creating a sum would be pretty easy.

    string sName;
    double dAmount;
    int sTotalNames = 0;
    double dAmountTotal = 0;
    double dAmountAverage;
    
    using (StreamReader sr = new StreamReader("Donations.txt"))
    {
        while (sr.Peek() != -1)
        {
            sName = sr.ReadLine();
            Console.WriteLine(sName);
    
            dAmount = Convert.ToDouble(sr.ReadLine());
            Console.WriteLine(dAmount);
            dAmountTotal += dAmount;
            sTotalNames++;
        }
        dAmountAverage = dAmountTotal / sTotalNames;
        Console.WriteLine("Sum = {0}", dAmountTotal );
        Console.WriteLine("Total Names = {0}", sTotalNames);
        Console.WriteLine("Average Amount = {0}", dAmountAverage);
        Console.WriteLine("Press any key to close");
        Console.ReadKey();
    }