Visual Studio C#控制台高分系统:文件文本格式化与读写问题
C#控制台测验程序高分保存解决方案
问题1:如何格式化文件文本以实现最简便的追加?
推荐用每行一条记录的CSV格式(逗号分隔),每条记录存为用户名,分数,这种格式结构简单,追加时直接往文件末尾加一行就行,不用读取整个文件,新手好上手。
示例代码:
string highscoreFilePath = "highscores.txt"; string username = "张三"; int scorePercent = 95; // 格式化一条记录 string newRecord = $"{username},{scorePercent}"; // 直接追加到文件末尾,自动换行 File.AppendAllLines(highscoreFilePath, new[] { newRecord });
如果文件不存在,AppendAllLines会自动创建文件;如果已存在,直接在末尾新增一行,完全不用处理原有内容。
问题2:如何隔离文件中的特定文本以按需追加内容?
先把文件里的内容解析成结构化的用户名和分数,之后就能轻松判断是否需要追加(比如只保留前N名,或者分数高于现有记录才追加)。
步骤1:读取并解析文件内容
string[] allRecords = File.ReadAllLines(highscoreFilePath); List<(string Username, int Score)> highscores = new List<(string, int)>(); foreach (string line in allRecords) { // 按逗号拆分每行内容 string[] parts = line.Split(','); // 验证格式是否正确,避免读取无效内容 if (parts.Length == 2 && int.TryParse(parts[1], out int score)) { highscores.Add((parts[0], score)); } }
步骤2:按需追加记录(示例:只保留前5名高分)
int maxEntries = 5; bool shouldAdd = true; // 如果已有记录达到上限,判断新分数是否比当前最低分高 if (highscores.Count >= maxEntries) { int lowestCurrentScore = highscores.Min(h => h.Score); shouldAdd = scorePercent > lowestCurrentScore; } if (shouldAdd) { // 添加新记录 highscores.Add((username, scorePercent)); // 按分数从高到低排序,只保留前5名 var sortedScores = highscores.OrderByDescending(h => h.Score).Take(maxEntries); // 重新写入文件 List<string> linesToWrite = sortedScores.Select(h => $"{h.Username},{h.Score}").ToList(); File.WriteAllLines(highscoreFilePath, linesToWrite); }
问题3:如何按自定义方式显示这些文本?
先把文件内容解析成结构化数据,之后就能按需求排序、格式化输出,比如做成整齐的高分榜,或者带排名的列表。
示例:格式化显示高分榜
// 先读取解析(复用问题2里的解析代码) List<(string Username, int Score)> highscores = new List<(string, int)>(); if (File.Exists(highscoreFilePath)) { string[] allRecords = File.ReadAllLines(highscoreFilePath); foreach (string line in allRecords) { string[] parts = line.Split(','); if (parts.Length == 2 && int.TryParse(parts[1], out int score)) { highscores.Add((parts[0], score)); } } } // 按分数降序排序 var sortedHighscores = highscores.OrderByDescending(h => h.Score); // 自定义显示样式 Console.WriteLine("=== 测验高分榜 ==="); // 格式化表头,左对齐用户名(占10位),右对齐分数(占5位) Console.WriteLine($"{"用户名",-10} | {"分数",5}"); Console.WriteLine("-------------------"); foreach (var entry in sortedHighscores) { Console.WriteLine($"{entry.Username,-10} | {entry.Score,5}%"); }
另一种显示方式(带排名)
int rank = 1; Console.WriteLine("=== 测验高分榜 ==="); foreach (var entry in sortedHighscores) { Console.WriteLine($"第{rank}名:{entry.Username} - {entry.Score}%"); rank++; }
内容的提问来源于stack exchange,提问作者AddisonJudah
相关产品推荐
相关产品推荐

