Считать из файла - C#

Узнай цену своей работы

Формулировка задачи:

По заданию, нужно вывести в файл out.txt фамилии и имена учащихся в порядке убывания их среднего балла. Но в коде ( и по заданию) предполагается, что оценок будет 3. МНЕ НУЖНО, чтобы количество оценок считывалось автоматически (гарантирую то, что количество будет одинаковое у всех студентов) и средний балл соответственно находился исходя из количества оценок.
Листинг программы
  1. using System;
  2. using System.IO;
  3. namespace Lab06
  4. {
  5. class Program
  6. {
  7. struct Student
  8. {
  9. public string Name;
  10. public double AverageScore;
  11. public uint Position;
  12. };
  13. static string Third_GetName(string Line)
  14. {
  15. string Ret = "";
  16. int Spaces = 2;
  17. foreach (char c in Line)
  18. {
  19. if ((int)c == 32) Spaces--;
  20. if ((Char.IsLetter(c) || ((int)c == 32)) && Spaces != 0)
  21. {
  22. Ret = Ret + c;
  23. }
  24. }
  25. return Ret;
  26. }
  27. static double Third_GetAverageScore(string Line)
  28. {
  29. uint Ret = 0;
  30. uint Score = 0;
  31. foreach (char c in Line)
  32. {
  33. if (Char.IsDigit(c))
  34. {
  35. Score = UInt16.Parse(c.ToString());
  36. if ((Score < 2 || Score > 5)) Console.WriteLine("Один из баллов за предмет не входит в средний балл, т.к он не в [2, 5]");
  37. else
  38. {
  39. Ret += Convert.ToUInt16(c.ToString());
  40. }
  41. }
  42. }
  43. return ((double)(Ret) / 3.0);
  44. }
  45. static void Third()
  46. {
  47. try
  48. {
  49. StreamReader f = new StreamReader("вход.txt");
  50. uint CountOfMembers = 0;
  51. try
  52. {
  53. CountOfMembers = Convert.ToUInt32(f.ReadLine());
  54. }
  55. catch (Exception e)
  56. {
  57. Console.WriteLine("Ошибка: {0}", e.Message);
  58. }
  59. Console.WriteLine("Количество учащихся: {0}", CountOfMembers);
  60. string[] DataList = new string[CountOfMembers];
  61. Student[] MemberList = new Student[CountOfMembers];
  62. for (int i = 0; i < CountOfMembers; i++)
  63. {
  64. DataList[i] = f.ReadLine();
  65. MemberList[i] = new Student();
  66. MemberList[i].Name = Third_GetName(DataList[i]);
  67. MemberList[i].AverageScore = Third_GetAverageScore(DataList[i]);
  68. }
  69. f.Close();
  70. StreamWriter _f = new StreamWriter("out.txt");
  71. uint counter = 0;
  72. uint[] ScoreMap = new uint[CountOfMembers];
  73. for (int i = 0; i < CountOfMembers; i++)
  74. {
  75. counter = 0;
  76. for (int j = 0; j < CountOfMembers; j++)
  77. {
  78. if (MemberList[i].AverageScore > MemberList[j].AverageScore) counter++;
  79. }
  80. MemberList[i].Position = CountOfMembers - counter;
  81. }
  82. Student[] t = new Student[CountOfMembers];
  83. for (int i = 0; i < CountOfMembers; i++) t[MemberList[i].Position - 1] = MemberList[i];
  84. for (int i = 0; i < CountOfMembers; i++) _f.WriteLine("{0} {1}", t[i].Name, t[i].AverageScore);
  85. _f.Close();
  86. }
  87. catch (Exception e)
  88. {
  89. Console.WriteLine("Ошибка: {0}\nФайл будет создан", e.Message);
  90. StreamWriter f = new StreamWriter("вход.txt");
  91. f.Close();
  92. }
  93. }
  94. static void Main (string[] args)
  95. {
  96. Third();
  97. Console.ReadKey();
  98. }
  99.  
  100. }
  101. }

Решение задачи: «Считать из файла»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6.  
  7. namespace ConsoleApplication5
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             using (StreamReader sr = new StreamReader(@"E:\1.txt", Encoding.Default))
  14.             {
  15.                 using (StreamWriter sw = new StreamWriter(@"E:\2.txt", true, Encoding.Default))
  16.                 {
  17.                     while (true)
  18.                     {
  19.                         string temp = sr.ReadLine();
  20.                         if (temp == null)
  21.                             break;
  22.                         String[] stringArr = temp.Split(' ');
  23.                         IEnumerable<double> intArr = stringArr[2].ToCharArray().Select((x) => Char.GetNumericValue(x)); ;
  24.                         double result = 0;
  25.                         foreach (var el in intArr)
  26.                             result += el;
  27.                         result = result / intArr.Count();
  28.                         foreach (var el in stringArr.Take(2))
  29.                             sw.Write(" " + el);
  30.                         sw.WriteLine(" " + result);
  31.                     }
  32.                 }
  33.             }
  34.         }
  35.     }
  36. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 4.125 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы