C#如何读取TXT文本内容并拆分存储为分数、姓名两个独立数组
修改后的完整实现代码
using System; using System.IO; class Program { static void Main() { string filename = @"marks.txt"; // 初始化数组,长度设为30足够容纳20行左右数据 int[] scores = new int[30]; string[] names = new string[30]; // 记录有效数据行数 int validCount = 0; try { using (StreamReader reader = new StreamReader(filename)) { string line = reader.ReadLine(); while (line != null && validCount < scores.Length) { // 拆分每行内容,按空格分割 string[] parts = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2 && int.TryParse(parts[0], out int score)) { scores[validCount] = score; names[validCount] = parts[1]; validCount++; } line = reader.ReadLine(); } } if (validCount == 0) { Console.WriteLine("文件中无有效成绩数据"); return; } // 统计最高分、最低分、总分 int maxScore = int.MinValue; int minScore = int.MaxValue; int totalScore = 0; string maxName = ""; string minName = ""; for (int i = 0; i < validCount; i++) { totalScore += scores[i]; if (scores[i] > maxScore) { maxScore = scores[i]; maxName = names[i]; } if (scores[i] < minScore) { minScore = scores[i]; minName = names[i]; } } // 计算平均分 double avgScore = (double)totalScore / validCount; // 输出统计结果 Console.WriteLine($"最高分:{maxScore},获得者:{maxName}"); Console.WriteLine($"最低分:{minScore},获得者:{minName}"); Console.WriteLine($"平均分:{avgScore:F2}"); // 写入80分以上人员到新文件 string outputFile = @"high_score_students.txt"; using (StreamWriter writer = new StreamWriter(outputFile)) { for (int i = 0; i < validCount; i++) { if (scores[i] > 80) { writer.WriteLine($"{scores[i]} {names[i]}"); } } } Console.WriteLine($"80分以上人员信息已写入{outputFile}"); } catch (FileNotFoundException) { Console.Error.WriteLine($"找不到文件 {filename}"); } catch (DirectoryNotFoundException) { Console.Error.WriteLine("文件路径中的目录不存在"); } catch (IOException) { Console.Error.WriteLine($"无法打开文件 {filename}"); } catch (Exception ex) { Console.Error.WriteLine($"处理过程中发生错误:{ex.Message}"); } } }
实现说明
- 数组存储:设置了长度为30的数组存储分数和姓名,完全满足20行左右数据的存储需求,读取时会自动跳过格式错误的行,不会导致程序崩溃
- 统计逻辑:遍历有效数据一次即可完成最高分、最低分、总分的计算,同时记录对应人员姓名,平均分保留两位小数输出
- 文件写入:80分以上的人员信息会自动写入同级目录下的
high_score_students.txt文件 - 异常处理:保留了原有所有文件相关的异常捕获逻辑,新增了通用异常捕获,处理过程中出现的任何问题都会给出明确提示
内容的提问来源于stack exchange,提问作者YeetLord05
相关产品推荐
相关产品推荐

