2014-12-02 4 views
0

studentID, studentName 및 성적 (별도의 목록)으로 구성된 StudentStruct (구조)를 사용하는 프로그램을 작성 중입니다. 이 프로그램은 순차적 텍스트 파일을 읽어야하며 사용자가 학생 추가, 특정 학생에게 성적 추가, 학생 이름 변경, 학생 삭제 등의 작업을 수행 할 수있는 방법을 포함합니다. 프로그램이 끝나면 이전 파일을 현재 프로그램 세션의 새로운 변경 사항으로 덮어 씁니다.C#의 목록 구조에 데이터를 읽는 방법?

제 질문은 텍스트 파일의 데이터를 목록 내의 개별 구조 변수로 어떻게 읽습니까?

내 텍스트 파일은 다음과 같다 :

목록 내에서 구조 변수가 작성되면
00000,Mimzi Dagger,100,50,75,70,45,10,98,83 
00001,Alexander Druaga,89,45,80,90,15,73,99,100,61 
00002,Nicholas Zarcoffsky,100,50,80,50,75,100,100 
00003,Kantmiss Evershot,50,100 

, 어떻게 위의 파일과 같은 형식으로 목록 구조의 내용으로 파일을 덮어합니까?

등급이 다양하고 다양하기 때문에 각 등급을 반복하여 성적 목록에 추가하는 방법은 무엇입니까?

어쩌면 이미 말할 수 있듯이 저는 C#을 처음 접했고 이것이 제 첫 프로젝트입니다. 어떤 도움이라도 대단히 감사하겠습니다!

class Program 
    { 
     static string pathSource = @"C:\schoolfiles\StudentGrades.txt"; 

     struct StudentStruct 
     { 
      public string studentID; 
      public string studentName; 
      public List<string> grades; 
     } 

     static void Main(string[] args) 
     { 
      StudentStruct student = new StudentStruct(); 
      List<StudentStruct> myList = new List<StudentStruct>(); 
      student.grades = new List<string>(); 
     } 

업데이트 : 여기에 내가 지금까지 함께 온 것입니다 :

for (int i = 0; i < fileLines.Length; i++) 
{ 
    output = fileLines[i]; 
    string[] outputArray = output.Split(','); 

    student.grades = new List<string>(); 
    student.studentID = outputArray[0]; 
    student.studentName = outputArray[1]; 

    for (int j = 2; j < outputArray.Length; j++) 
    { 
     student.grades.Add(outputArray[j]); 
    } 

    myList.Add(student); 

UPDATE : 위의 코드는 멋지고 밖으로 일했다. 다음은이 질문에 관련된 내 코드의 상단 부분입니다 :

static void Main(string[] args) 
    { 
     //Declare variables 
     string output; 

     //Read the File into an array 
     string[] fileLines = File.ReadAllLines(PathSource); 

     StudentStruct student = new StudentStruct(); 
     List<StudentStruct> myList = new List<StudentStruct>(); 



     for (int i = 0; i < fileLines.Length; i++) 
     { 
      output = fileLines[i]; 
      string[] outputArray = output.Split(','); 

      student.grades = new List<string>(); 
      student.studentID = outputArray[0]; 
      student.studentName = outputArray[1]; 

      for (int j = 2; j < outputArray.Length; j++) 
      { 
       student.grades.Add(outputArray[j]); 
      } 

      myList.Add(student); 
     } 

     MainMenu(myList); 
    } 

그리고 내가 이런 짓을 파일로 다시 목록을 추가 :

static void ExitModule(List<StudentStruct> myList) 
    { 
     //Declare variables 
     string inputChoice = null; 
     string output = null; 

     System.IO.StreamWriter file = new System.IO.StreamWriter(PathSource); 

     Console.Clear(); 
     Console.WriteLine("Are You Sure You Want To Exit The Program? Y/N"); 
     inputChoice = Console.ReadLine(); 

     if (inputChoice == "Y" || inputChoice == "y") 
     { 
      for (int i = 0; i < myList.Count; i++) 
      { 
       output = (myList[i].studentID + "," + myList[i].studentName); 

       for (int j = 0; j < myList[i].grades.Count; j++) 
       { 
        output += ("," + myList[i].grades[j]); 
       } 

       file.WriteLine(output); 
      } 

      file.Close(); 
      Environment.Exit(0); 
+0

중첩 된 목록으로 목록을 전달하는 방법에 대한 구문 – AsfK

+0

(새 학생 구조 매번 사용) 목록에 노드를 추가 한 후 (쉼표 따라) 및 라인을 구문 분석 할 수 – Wallatrixx

+0

주석에 코드를 게시하지 마십시오. 질문을 편집하고 코드를 입력하십시오. –

답변

2

을 위해 일하고, 당신이에 대한 data structures을 배울 수있는 좋은 시간이 될 수 있습니다. 이렇게하면 텍스트 파일에서 읽은 정보를 효율적으로 저장하여 레코드 수정 후 훨씬 쉽게 작성할 수 있습니다.

  • System.IO.File.ReadLines(pathSource) 방법 (텍스트 파일
  • 당신은 거의 절대 C#에서 struct를 사용해서는 안 각각의 라인을 읽기 시작하기에 좋은 장소가 될 것입니다 : 여기

    다른 임의의 포인터의 커플 특히 당신의 예제 에서처럼 변경 가능하다.) 당신이 그 의미와 목적에 정통하지 않는 한. class 대신
+0

규정 중 하나는 구조를 사용해야하고 클래스를 1 개만 가질 수 있다는 것입니다. – Wallatrixx

+0

과제의 정확한 표현이'class'만으로'struct'를 사용한다면, 당신이해야 할 일이라고 생각합니다. 이런 식으로'struct'를 사용하는 것은 아주 잘못되었음을 잊지 말고, 할당이 완료되면 이런 방식으로 수행했는지 잊어 버리십시오. –

+0

네, .ReadLines를 사용하여 파일을 배열로 읽어 들였습니다. 그런 다음 분할하여 for 루프를 사용하여 변수를 목록 요소에 넣었습니다. 감사! – Wallatrixx

0

이 코드를보십시오. 이 숙제가 명확하기 때문에 그것이 나

class Program 
    { 
     static string pathSource = @"C:\schoolfiles\StudentGrades.txt"; 

     struct StudentStruct 
     { 
      public string studentID; 
      public string studentName; 
      public List<string> grades; 
     } 

     static void Main(string[] args) 
     { 
      StudentStruct student = new StudentStruct(); 
      List<StudentStruct> myList = new List<StudentStruct>(); 
      student.grades = new List<string>(); 

      // get all lines from text file 
      string[] allLinesFromFile = File.ReadAllLines(pathSource); 

      // iterate through each line and process it 
      foreach(string line in allLinesFromFile) 
      { 
       // split each line on ',' 
       string[] sections = line.Split(','); 
       student.studentID = sections[0]; 
       student.studentName = sections[1]; 

       // use this loop to add numbers to list of grades 
       for(int i =2; i < sections.Length; i++) 
       { 
        student.grades.Add(sections[i]); 
       } 

       // add this student to list 
       myList.Add(student); 

       // create new object of student 
       student = new StudentStruct(); 
       student.grades = new List<string>(); 
      } 
     } 
0

몇 가지를 사용하십시오.

(1) 왜 선생님/교수님이 여기 구조체를 사용하게 될지 잘 모르겠습니다. 수업이 훨씬 더 적절합니다.I actually cringed when I first saw the code

(2) CONST는 또한 정적임을 의미로 무언가를 가진 것은 "pathSource"

(3) 속성 "pathSource" -> "PathSource"를 대문자로한다

(4) 당신은 책임을 분리해야 ... 넣어하지 않으려 고 본문의 모든 것

(5) StudentStruct 외부의 성적표를 작성하지 않아도 오류가 발생할 수 있습니다. 즉 NullPointerException ... 기본적으로 구조체는 자체 포함되어야합니다.

(6) 모든 것이 컴파일되어야합니다. 나는 그것을 시험하지 않았다. 문제가있는 경우. 저에게 알려주세요.

Program { 
    private const string PathSource = @"C:\schoolfiles\StudentGrades.txt"; 

    private struct StudentStruct 
    { 
     public string StudentID; 
     public string StudentName; 

     private List<string> _gradeList; 

     public List<string> GradeList 
     { 
      // if _gradeList is null create a new instance 
      get { return _gradeList ?? (_gradeList = new List<string>()); } 
      private set { _gradeList = value; } 
     } 
    } 

    private static void Main(string[] args) 
    { 
     var studentFile = File.ReadAllLines(PathSource); 
     // If you haven't learned about delegates or extensions methods... 
     // You can just change it to a foreach statement 
     var myList = studentFile.Select(GetStudent).ToList(); 

     // make sure we have everything 
     foreach (var studentStruct in myList) 
     { 
      Console.WriteLine("{0} {1}", studentStruct.studentName, studentStruct.studentID); 
      foreach (var grade in studentStruct.GradeList) { Console.Write(grade + " "); } 
      Console.WriteLine(); 
     } 
    } 

    private static StudentStruct GetStudent(string line) 
    { 
     var student = new StudentStruct(); 
     var studentDelimited = line.Split(','); 

     student.studentID = studentDelimited[ 0 ]; 
     student.studentName = studentDelimited[ 1 ]; 

     for (int i = 2; i < studentDelimited.Length; i++) { student.GradeList.Add(studentDelimited[ i ]); } 

     return student; 
    } 
} 
쉽게 나는 문제가 밖으로내는 데으로 나는,하지만 그것을 테스트 할 수 없습니다
+0

성적은 목록 내의 목록이므로 각 학생마다 새로운 성적 목록이 필요할 때마다 새 목록을 초기화해야한다고 생각했습니다. 내 선생님이 나중에 코드를 작성하는 더 쉽고 효율적인 방법을 보여주기 위해이 방법으로 우리를 만들고 있다고 생각합니다. – Wallatrixx

+0

My Main() 메서드를 사용하여 파일을 목록에로드해야했습니다. 프로그램에 필요한 다른 모든 기능을위한 별도의 메소드가 있습니다. 귀하의 조언에 감사드립니다. 정말 감사. – Wallatrixx

+0

문제 없습니다 ... 행운을 빈다. –