My code won`t add numbers together correctly when reading them from file

353 views Asked by At

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);
            }
        }
    }
}
1

There are 1 answers

1
Trevor On

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.