user7115764
user7115764

Reputation: 63

Reading doubles from a .txt file and copying them to a new .txt file (Streamreader/Streamwriter)

static void Main(string[] args)
    {
        Console.Write("Enter the name of the file to open: ");
        string input = Console.ReadLine();
        Console.Write("Enter the name of the output file: ");
        string output = Console.ReadLine();
        var InFile = new StreamReader(input);
        int TotalD = 0;
        StreamWriter OutFile = new StreamWriter(output);
        Console.WriteLine();
        try
        {
            using (InFile)
            {
                double DInput = 0;
                while (DInput == double.Parse(InFile.ReadLine()))
                {
                    while (!InFile.EndOfStream)
                    {
                        DInput = double.Parse(InFile.ReadLine());
                        double DOutput = DInput * 2;
                        InFile.Close();

                        using (OutFile)
                        {
                            OutFile.WriteLine(DOutput);
                        }

                    }
                    InFile.Close();

                }
            }
            using (StreamReader r = new StreamReader(input))
            {
                TotalD = 0; 
                while (r.ReadLine() != null) { TotalD++; }

            }
        }
        catch (IOException Except)
        {
            Console.WriteLine(Except.Message);
        }
        Console.WriteLine("There were {0} doubles copied to {1}.", TotalD, output);
        Console.WriteLine();
        Console.Write("Press <enter> to exit the program: ");
        Console.Read();
    }

Ok so I've asked this question before but the problem was that I didn't know the input.txt file had to be manually written instead of generated like I was doing before. This current version also runs without error messages. The only issue now is that output.txt is completely blank. Any help would be much appreciated!

The idea of this project is to read the doubles from input.txt:

1.5
2.3
3
4.7
5

And write them to output.txt only times 2:

3.0
4.6
6
9.4
10

Upvotes: 0

Views: 68

Answers (1)

JuanR
JuanR

Reputation: 7783

 string input = @"C:\temp\testinput.txt";
 string output = @"C:\temp\testoutput.txt";
 using (var reader = new StreamReader(input))
 {
     using (var writer = new StreamWriter(output))
     {
         var line = reader.ReadLine();
         while (line != null)
         {
             var value = float.Parse(line);
             var result = value * 2;
             writer.WriteLine(result);
             line = reader.ReadLine();
         }
     }                
 }

Format the output to the file so it looks like what you want.

Upvotes: 1

Related Questions