2014-09-28 3 views
0

계속 하시겠습니까? 'y'를 입력하면이 프로그램을 반복 실행하는 데 문제가 있습니다. 나는 그런 식으로 프로그래밍에 익숙하지 않으므로 어떤 도움도 크게 받으실 수 있습니다. 나는 코드의 끝에서 계속하기를 원한다면 do/while을 main과 k 사용자로 추가하는 것이 최선이라고 생각했지만, 사용자 입력을 위해 이전 방법을 호출하지 않으면 빨리 작동하지 않는다는 것을 깨달았다. 출력합니다. 그것이 문제가 발생하는 곳입니다.C++ do/while 루프 및 호출 함수?

도움을 주셔서 다시 한 번 감사드립니다! 변수 s1s2는 DO-While 루프, 그들은 각 반복에 다시됩니다 내부에 있기 때문에

/* 

• Ask the user if they want to enter the data again (y/n). 
• If ’n’, then the program ends, otherwise it should clear the student class object and 
repeat the loop (ask the user to enter new data...). 

*/ 
#include <iostream> 
#include <cstdlib> 
#include <string> 

using namespace std; 

class Student { 
    public: 
    Student(); 
    ~Student(); 
    void InputData();  // Input all data from user 
    void OutputData();  // Output class list to console 
    void ResetClasses();  // Reset class list 
    Student& operator =(const Student& rightSide); // Assignment operator 

private: 
    string name; 
    int numClasses; 
    string *classList; 
}; 


//array intialized to NULL 
Student::Student() { 
    numClasses = 0; 
    classList = NULL; 
    name = ""; 
} 

//Frees up any memory of array 
Student::~Student() { 

if(classList != NULL) { 
    delete [] classList; 
} 
} 

// This method deletes the class list 
// ====================== 
void Student::ResetClasses() { 
    if(classList != NULL) { 
     delete [ ] classList; 
     classList = NULL; 
} 
numClasses = 0; 
} 



//inputs all data from user (i.e. number of classes) 
//using an array to store classes 
void Student::InputData() { 
int i; 

// Resets the class list in case the method 
// was called again and array wasn't cleared 
ResetClasses(); 

cout << "Enter student name." << endl; 
getline(cin, name); 
cout << "Enter number of classes." << endl; 
cin >> numClasses; 
cin.ignore(2,'\n'); // Discard extra newline 
if (numClasses > 0) { 
    //array to hold number of classes 
    classList = new string[numClasses]; 
    // Loops through # of classes, inputting name of each into array 
    for (i=0; i<numClasses; i++) { 
     cout << "Enter name of class " << (i+1) << endl; 
     getline(cin, classList[i]); 
    } 
} 
cout << endl; 
} 

// This method outputs the data entered by the user. 
void Student::OutputData() { 

int i; 
cout << "Name: " << name << endl; 
cout << "Number of classes: " << numClasses << endl; 
for (i=0; i<numClasses; i++) { 
    cout << " Class " << (i+1) << ":" << classList[i] << endl; 
} 
cout << endl; 
} 


/*This method copies a new classlist to target of assignment. If the operator isn't overloaded  there would be two references to the same class list.*/ 
Student& Student::operator =(const Student& rightSide) { 

int i; 
// Erases the list of classes 
ResetClasses(); 
name = rightSide.name; 
numClasses = rightSide.numClasses; 

// Copies the list of classes 
if (numClasses > 0) { 
    classList = new string[numClasses]; 
    for (i=0; i<numClasses; i++) { 
     classList[i] = rightSide.classList[i]; 
    } 
} 
return *this; 
} 

//main function 
int main() { 
    char choice; 
do { 
// Test our code with two student classes 
Student s1, s2; 

s1.InputData();  // Input data for student 1 
cout << "Student 1's data:" << endl; 
s1.OutputData();  // Output data for student 1 

cout << endl; 

s2 = s1; 
cout << "Student 2's data after assignment from student 1:" << endl; 
s2.OutputData();  // Should output same data as for student 1 

s1.ResetClasses(); 
cout << "Student 1's data after reset:" << endl; 
s1.OutputData();  // Should have no classes 

cout << "Student 2's data, should still have original classes:" << endl; 
s2.OutputData();  // Should still have original classes 

cout << endl; 
cout << "Would you like to continue? y/n" << endl; 
cin >> choice; 
if(choice == 'y') { 

    void InputData();  // Input all data from user 
    void OutputData();  // Output class list to console 
    void ResetClasses();  // Reset class list 
} 
} while(choice == 'y'); 

return 0; 
} 
+0

classlist'vector '을 만들면 더 이상 삭제하거나 할당 연산자 또는 복사 생성자 (잊어 버린)를 만들 필요가 없습니다. 그냥 작동합니다. –

답변

0

은 그냥

if(choice == 'y') { 

    void InputData();  // Input all data from user 
    void OutputData();  // Output class list to console 
    void ResetClasses();  // Reset class list 
} 

제거. (생성자는 정의에서 호출되고 소멸자는 루프의 닫는 중괄호에서 호출되어 choice == 'y'을 테스트하고 반복합니다.)

다른 문제는 표준 입력이 s1.InputData()과 다시 호환되는 상태가 아닌 것입니다. >> 추출 연산자를 사용하여 choice을 읽었으므로 첫 번째 공백에서 구문 분석이 중단되고 버퍼에 새 라인이 남았습니다. Student::InputDatagetline이라면, 버퍼에 새 라인이 있고 추가 입력을 기다리지 않을 것입니다.

numClasses을 읽은 후 cin.ignore을 사용한 것과 같은 이유입니다. 여기서도 똑같이하고 싶을 것입니다.

+0

이들은 "변수"가 아닙니다. 함수 선언입니다. OP와 비슷한 이름을 가진 함수를 비슷한 범위로 재 선언하기보다는 전역 범위에서 호출하도록 의도 된 것 같습니다. 나는이 전체 조건부 블록을 제거하는 것이 달성 할 수있는 것을 보지 못한다. –

+0

그래도 사용자 입력을 다시 묻지 않고 프로그램을 다시 실행하기 때문에 도움이되지 않습니다. 나는 행운과 함께 입력과 출력 함수를 다른 방법으로 호출 해 보았습니다. 어떤 힌트 또는 아이디어? – NoobCoderChick

+0

@ LightnessRacesinOrbit : 의견을 남겨주세요. 그것들은 변수가 아니지만 나는 결코 그런 변수가 아니라고 말했습니다. 나는 변수가 루프 안에 있다고 말했다. 음, 그들은 그렇습니다. 귀하의 의견은 완전히 그 요점을 놓쳤습니다. 조건부 블록을 제거하면 어떤 결과가 나오는지 보지 못하면 ... 질문에서 코드를 보았습니까? –