|
| 1 | +// Example purpose: show the module flow with clear, beginner-friendly steps. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.IO; |
| 5 | + |
| 6 | +class Program |
| 7 | +{ |
| 8 | + static bool TryParseScoreRow(string line, out string name, out int score) |
| 9 | + { |
| 10 | + name = string.Empty; |
| 11 | + score = 0; |
| 12 | + |
| 13 | + // Intent: normalize row parsing so the main flow can stay focused on I/O steps. |
| 14 | + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); |
| 15 | + // Intent: guard malformed rows before numeric parsing logic runs. |
| 16 | + if (parts.Length != 2 || !int.TryParse(parts[1], out score)) |
| 17 | + { |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + name = parts[0]; |
| 22 | + return true; |
| 23 | + } |
| 24 | + |
| 25 | + static void Main() |
| 26 | + { |
| 27 | + // Program flow: prepare input, parse rows, then generate a summary file. |
| 28 | + string runDirectory = Path.Combine(Path.GetTempPath(), "learn-lang-file-io-csharp"); |
| 29 | + Directory.CreateDirectory(runDirectory); |
| 30 | + string inputPath = Path.Combine(runDirectory, "scores.txt"); |
| 31 | + string outputPath = Path.Combine(runDirectory, "summary.txt"); |
| 32 | + |
| 33 | + if (!File.Exists(inputPath)) |
| 34 | + { |
| 35 | + File.WriteAllLines(inputPath, new[] { "ana 90", "bob 82", "invalid row", "carla 95" }); |
| 36 | + } |
| 37 | + |
| 38 | + int validRows = 0; |
| 39 | + int sum = 0; |
| 40 | + |
| 41 | + using (StreamReader reader = new StreamReader(inputPath)) |
| 42 | + { |
| 43 | + string? line; |
| 44 | + // Intent: iterate through file rows in a deterministic order. |
| 45 | + while ((line = reader.ReadLine()) is not null) |
| 46 | + { |
| 47 | + if (!TryParseScoreRow(line, out string name, out int score)) |
| 48 | + { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + validRows++; |
| 53 | + sum += score; |
| 54 | + // Intent: print parsed rows so learners can verify intermediate state. |
| 55 | + Console.WriteLine($"{name} -> {score}"); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (validRows == 0) |
| 60 | + { |
| 61 | + Console.WriteLine("No valid rows found."); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + double average = (double)sum / validRows; |
| 66 | + |
| 67 | + using (StreamWriter writer = new StreamWriter(outputPath, false)) |
| 68 | + { |
| 69 | + writer.WriteLine($"Rows: {validRows}"); |
| 70 | + writer.WriteLine($"Average: {average:F2}"); |
| 71 | + } |
| 72 | + |
| 73 | + Console.WriteLine($"Summary written to {outputPath}"); |
| 74 | + } |
| 75 | +} |
0 commit comments