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);
}
}
}
}
The main issue is because of
reader.ReadLine() != null
that check. Then again, you are reading the next lineint.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.
There are other ways this could be accomplished as well, but isn't the concern for this post.