Joseph

Joseph

  • NA
  • 14
  • 17.2k

streamreader;

Apr 20 2011 8:15 PM
The program will have the user input the name of the to be opened. If the file could not be opened, or any exceptions were thrown during the file read operation, an error message will be displayed and the program will exit.

If the file operations are okay, the program will calculate the average value of the doubles stored in the file (one value per line) and display it. Display the values as they are read in from the file.

Output should be like this:


Enter the name of the file to open: junk.txt
A file failure occured.

Enter the name of the file to open: numbers.txt

52.3
123.4
45.6
78.4
112.3

Average of the doubles is 82.4

Press any key to continue:


my code is this:it won`t open the numbers.txt.

using System;
using System.IO;

        static void Main(string[] args)
        {
            string sOpen = "";
            string sInput = "";
            double dValue = 0.0;
            double dSum = 0.0;
            double dAverage = 0.0;
            int iCount = 0;
            StreamReader Infile;
           

            Console.WriteLine("{0,40}", "Question 2");

            try
            {
               Console.Write("\nEnter the name of the file to open: ");
               sOpen = Console.ReadLine();
                   
               Infile = new StreamReader(sInput);

               while (Infile.EndOfStream == false)
               {
                   sInput = Infile.ReadLine();
                   Console.WriteLine(sInput);
                   dValue = double.Parse(sInput);
                   dSum = dSum + dValue;
                   iCount++;
               }
               dAverage = dSum / iCount;
               Console.WriteLine("\nAverage value of the doubles is {0}", dAverage);

            }
            catch (Exception)
            {
                Console.WriteLine("A file failure occured.");
            }

            Console.Write("\nPress any key to continue.");
            Console.ReadLine();
        }


Answers (5)