2016-07-01 2 views
-1

저는 C++을 처음 접했고 실수를 저에게 배웠습니다. 파일이 있고 파일 내에 다음 형식의 데이터가 포함되어 있습니다.파일에서 입력을 루프에 저장하고 배열 변수에 저장하는 방법은 무엇입니까?

"문자열", "문자열", 문자 및 숫자가 100 개 항목입니다. "Billy Joel A 96 Tim McCan B 70".

나는이 항목을 클래스 배열에 저장하려고합니다. 어쩌면 인스턴스 또는 개체를 의미 할 수도 있습니다.

이것은 내 나쁜 시도입니다. 다음 학생 정보를 얻지 못하는 이유는 ... 왜 이렇게 처리 할 수 ​​있을까요? 그래서 나는 모든 학생 이름을 얻을 수 있니? 물건을 infile하기 위해 100 개의 변수를 만들지 않아야합니다.

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 


class Student{ 
private: 
    int grade; 
    char grade_letter; 
public: 
    struct Student_info(){ 
     void set_firstname(); 
     void set_lastname(); 
     string get_firstname(); 
     string get_lastname();   
    }; 


}myStudent_info; 

/// Set/get code below but left out. 

int main() 
{ 
    Student myStudent[100]; 

    ifstream myfile("input.txt"); 
    if (myfile.is_open()) 
    { 
     string a, b; 
     char c; 
     int d; 

     myfile >> a >> b >> c >> d; 
     for (int i = 0; i < 100; i++) { 
      myStudent[i].myStudentInfo.set_firstname(a); 
      myStudent[i].myStudentInfo.set_lastname(b); 
      /// the rest of variables...etc      
     } 

     myfile.close(); 
    } 
    //Exit 
    cout << endl; 
    system("pause"); 
    return 0; 
} 
+2

'myStudent [100]'배열을 만들어 정보를 저장하십시오. – user1336087

+0

'myfile >> a >> b << c << d; '''c '가 나오기 전에''''이라고 가정하고,'d'는 오타라고 가정합니다. – drescherjm

+0

'Student myStudent;는'Student myStudent [100];이어야합니다. – drescherjm

답변

3

1 학생의 데이터 만 입력 한 다음 100 회 반복합니다. 당신이 입력 (100 명) 학생의 데이터를 원하고 각각을 저장하는 경우 이것이 당신이

for (int i = 0; i < 100; i++) { 
    myfile >> a >> b >> c >> d; 
    myStudent[i].myStudentInfo.set_firstname(a); 
    myStudent[i].myStudentInfo.set_lastname(b); 
    /// the rest of variables...etc      
} 

대신

myfile >> a >> b << c << d; 
for (int i = 0; i < 100; i++) { 
    myStudent[i].myStudentInfo.set_firstname(a); 
    myStudent[i].myStudentInfo.set_lastname(b); 
    /// the rest of variables...etc      
} 
+0

어쩌면 엉망 이었지만 그렇게하려고했습니다. 텍스트 파일에서 100 명의 동일한 학생 이름과 다른 학생 이름을 모두 할당했습니다. –

+0

@drescherjm과 같이 'Student myStudent;'대신 'student myStudent [100];을 입력하십시오. –

0

의 무엇을해야 당신의 권리를 heres 트랙 내가 어떻게 할 것인지의 내 생각에. 그러나 요점은 메인에있는 벡터 또는 배열의 학생을 만들어야한다는 것입니다.

class Student{ 
private: 
    int grade; 
    char grade_letter; 
    string firstname; 
    string lastname; 
public: 
     Studnet(); 
     void set_firstname(string x); 
     void set_lastname(string x); 
     void set_letter(char x); 
     void set_grade(int x);   
}; 


int main() { 
    Student x; 
    std::vector<Student> list(100); 

    sting input; 

    ifstream myfile("input.txt"); 
    if (myfile.is_open()) { 
     while(getline(myfile, input)) { 

      // divide input variable into parts 
      // use set functions to set student x's values 
      // push student x into vector of students list using "list.push_back(x);" 

     } 
     myfile.close(); 
    } 
    return 0; 
} 
+0

샘플 입력 데이터에 줄 바꿈이 없습니다. –

관련 문제