I've seen a million answers about StreamReader and how to write to a file, but NOTHING about how to read a file, do a mathematical process on what is read and write the ANSWER to that process in another file. I need this for homework, please. My code in C#, .NET 2008 is as follows:

    private void calcButton_Click(object sender, EventArgs e)
    {
        using (StreamReader sr = new StreamReader("output.txt"))

        {
            double score;
            while ((score = sr.ReadLine()) != null)
            {
                score = score + score;
                ++count;

                averageScore = (double)score / count;
            }
            Console.WriteLine(@"C:\output.txt", averageScore, true);
        }
    }

and I am getting the error "Cannot implicitly convert type 'string' to 'double' " on sr.ReadLine code. What do I write and where do I write it so that I can get a number and do the calculations?? If I can get this done, then I can start on an Address Book application for my final... Thanks in advance...

Recommended Answers

All 4 Replies

>while ((score = sr.ReadLine()) != null)
ReadLine returns a string, not a double. There's no implicit conversion from string to double, so you have to make the conversion manually:

string line;

while ( ( line = sr.ReadLine() ) != null ) {
  double score = double.Parse ( line );

  //...
}

Thanks for the response - now getting a new error:

private void calcButton_Click(object sender, EventArgs e)
    {
        using (StreamReader sr = new StreamReader("output.txt"))
        {
            double score;
            string line;
            while ((line = sr.ReadLine()) != null)
                double score = double.Parse (line);
            {
                score = score + score;
                ++count;

                averageScore = (double)inValue / count;
            }

            Console.WriteLine(@"C:\output.Txt", averageScore, true);
            }
        }

"Embedded statement cannot be a declaration or labeled statement"   Line under "double" in
 "double score = double.Parse (line)

Move the variable up. You can not redeclare the variable in the while statement.

Whoops, you have even more problems, here is a corrected version.

string line;
double score = 0;
count = 0;
while ((line = sr.ReadLine()) != null)
{
    score += double.Parse (line);
    count++;
}
averageScore = (double)inValue / count;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.