0

I want to add together numbers from a file. Numbers are 31 32 45 65 67 54 43 78 98 33 14 25. Answer should be 585, but code gives 287. Where do I go wrong and how to fix it?

using System;
using System.IO;

namespace TaaviSimsonTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TextReader reader = File.OpenText("C:\\temp\\andmed.txt"))
            {
                int sum = 0;
                while (reader.ReadLine() != null)
                {
                    int i = int.Parse(reader.ReadLine());
                    sum += i;
                }
                Console.WriteLine(sum);
            }
        }
    }
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 1
    You could use `File.ReadLines` to get an `IEnumerable` instead of explicitly reading the lines. You can combine this with LINQ to calculate the sum, eg `File.ReadlLines(..).Select(l=>int.Parse(l)).Sum();` – Panagiotis Kanavos Oct 01 '20 at 18:10
  • Another case where using the **[free, easy to use, built in debugger](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)** would allow you to solve this yourself. – Ňɏssa Pøngjǣrdenlarp Oct 01 '20 at 19:00

1 Answers1

5

I want to add together numbers from a file. Numbers are 31 32 45 65 67 54 43 78 98 33 14 25. Answer should be 585, but code gives 287

The main issue is because of reader.ReadLine() != null that check. Then again, you are reading the next line int.Parse(reader.ReadLine());

What is happening is you are reading the first line, then reading again and getting that value, so you are skipping every other entry. Instead read it only once and then do something with that assignment.

using (TextReader reader = File.OpenText("C:\\temp\\andmed.txt"))
{
   int sum = 0;
   string line = string.Empty;
   while ((line = reader.ReadLine()) != null)
   {
      int i = int.Parse(line);
      sum += i;
   }
   Console.WriteLine(sum);
}

There are other ways this could be accomplished as well, but isn't the concern for this post.

Trevor
  • 7,777
  • 6
  • 31
  • 50
  • 1
    Thank you. So if I understand correctly, I have to first define every line as a string? Then say that string equals reader. readline() and that cannot be null. While condition. and then the code basically goes on as it was? – Taavi Simson Oct 03 '20 at 06:24