2011-03-29 7 views
0

파일 이름에 대한 사용자 입력을 허용하는 프로그램을 작성하려고합니다. 거기에서 파일의 숫자를 배열에 저장하고 정렬 한 다음 표시합니다. 그러나, 나는 out-of-bound 배열에 접근하는 것과 비슷한 큰 숫자를 얻고있다. 그러나 나는 디버거로부터 알 수있다. 디버거를 통해보고를 바탕으로배열이 올바르게 지정되지 않았습니다.

15 
67 
76 
78 
56 
45 
234 

, 내가 scoreCounter가 제대로 증가되는 것을 알 수 있습니다 및 newScore 다음 값을 포함, 그래서 :

#include <iostream> 
using namespace std; 

class TestScores 
{ 
public: 
    TestScores(); 

    TestScores(int scores); 

    ~TestScores(); 

    void AddScore(int newScore); 

    void DisplayArray(); 

    void SortScores(); 

    bool ArraySorted(); 

    int AvgScore(); 

private: 
    int *scoresArray; //Dynamically allocated array 
    int numScores; //number of scores input by user 
    int scoreCounter; 
    const static int default_NumArrays=10; //Default number of arrays 
}; 

#include <iostream> 
#include "TestScores.h" 

TestScores::TestScores() 
{ 
    scoresArray=new int[default_NumArrays]; 
    scoreCounter=0; 
    numScores=default_NumArrays; 
} 

TestScores::TestScores(int scores) 
{ 
    scoresArray=new int[scores]; 
    numScores=scores; 
    scoreCounter=0; 
    for(int i=0; i<scores;i++) 
     scoresArray[i]=0; 
} 

TestScores::~TestScores() 
{ 
    delete[] scoresArray; 
} 

void TestScores::AddScore(int newScore) 
{ 
    if(scoreCounter<numScores){ 
     scoresArray[scoreCounter]=newScore; 
     scoreCounter++; 
    } 
    else 
     cout<<"More scores input than number of scores designated"<<endl; 
} 

void TestScores::DisplayArray() 
{ 
    for(int i=0; i<numScores; i++) 
     cout<<scoresArray[i]<<endl; 
    cout<<endl<<"This is scoresArray"<<endl; 
} 

bool TestScores::ArraySorted() 
{ 
    for(int i=0; i<(scoreCounter-1);i++){ 
     if(scoresArray[i]<=scoresArray[i+1]) 
      continue; 
     else 
      return false; 
    } 
    return true; 
} 

void TestScores::SortScores() 
{ 
    int tempValue; 

    while(ArraySorted()!=true){ 
     for(int i=0; i<(scoreCounter-1); i++){ 
      if(scoresArray[i]<=scoresArray[i+1]) 
       continue; 
      else{ 
       tempValue=scoresArray[i+1]; 
       scoresArray[i+1]=scoresArray[i]; 
       scoresArray[i]=tempValue; 
      } 
     } 
    } 
} 


int TestScores::AvgScore() 
{ 
    int sumScores=0; 

    if(scoreCounter>0){ 
     for(int i=0; i<scoreCounter; i++) 
      sumScores+=scoresArray[i]; 
     return (sumScores/scoreCounter); 
    } 
    else{ 
     cout<<"There are no scores stored."<<endl; 
     return 0; 
    } 
} 

#include "TestScores.h" 
#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 
//Function prototypes 
bool FileTest(ifstream& inData); 
void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores); 

int main() 
{ 
    int newNumScores=0; 
    string inputFile; //Contains name of the user file being used 

    //Opening file stream 
    ifstream inData; 

    //User prompt for input file 
    cout<<"Please enter the file name containing the student scores you wish to " 
     <<"have stored, sorted, and displayed."<<endl; 

    cin>>inputFile; 

    //Opening file streams 
    inData.open(inputFile.c_str()); 

    while(FileTest(inData)==false){ 
     cout<<"I'm sorry, the file you entered was not a valid file. " 
      <<"Please enter another file name, or enter q to exit"<<endl; 
     cin>>inputFile; 
     if(inputFile=="q") 
      return 0; 

     //Opening file streams 
     inData.open(inputFile.c_str()); 
    } 

    inData>>newNumScores; 
    TestScores satScores(newNumScores); //Instantiating TestScores variable 
    StoreScores(inData, newNumScores, satScores); //Storing scores into array 

    satScores.DisplayArray(); 
    satScores.SortScores(); 
    satScores.DisplayArray(); 
    cout<<endl<<"This is the array after sorting"<<endl<<endl; 

    cout<<"This is the average score "<<satScores.AvgScore()<<endl; 

    //Program pauses for user input to continue 
    char exit_char; 
    cout<<"\nPress any key and <enter> to exit\n"; 
    cin>>exit_char; 

    inData.close(); 

    return 0; 
} 


bool FileTest(ifstream& inData) 
{ 
    if(!inData) 
    { 
     cout<<"Your file did not open.\n"; 
     return false; 
    } 
    return true; 
} 


void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores) 
{ 
    int userScore; 
    while(inData>>userScore){ 
     satScores.AddScore(userScore); 
    } 
} 

내 테스트 파일은 다음 random.dat하고 포함 배열에 왜 저장되지 않습니까? 도움을 주셔서 감사합니다

+0

정확히 큰 숫자는 무엇입니까? 그것은 [이 질문과 내 대답]의 문제와 관련이 있습니다 (http://stackoverflow.com/questions/5447002/how-to-read-a-birthday-with-symbols-and-from-a-txt -file/5447085 # 5447085)가 C++이 인식하지 못하는 유니 코드로 인코딩 된 텍스트 파일입니다. – Xeo

+0

이렇게 보입니다. 15 10 자리 # neg입니다. 8 자리 숫자 # neg 10 자리 숫자 및 몇 자리의 음수 10 자리 숫자 – ChadM

+0

@Chad : 좋아요, 코드로 빠른 테스트를했는데 앱을 종료 한 후 동일한 숫자와 어설 션 오류가 발생했습니다. 오류를 조사하는 동안 꾸준히 노력하십시오. :) – Xeo

답변

2

좋아요, 문제는 아주 간단합니다. satScoresStoreScores으로 전달합니다. (실제로 newNumScores 변수를 사용하지 않는 Btw는.)

void StoreScores(ifstream& inData, int& newNumScores, TestScores& satScores) 

을 출력은 다음 예상대로 : 이것은 단지 해결하기 위해 다음에 StoreScores의 서명을 변경, 로컬 복사본을 채울 것입니다

15 
67 
76 
78 
56 
45 
234 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 

코드 개선을 위해 GMan의 의견과 Ben의 답변을 참조하십시오.

+0

예 어떻게 작동합니까? btw, newNumScores를 어떻게 사용하지 않습니까?나는 15 개의 배열이 있다는 사실에 의해 확인되는 배열의 수를 정의하는 newNumScores로 생각한 매개 변수화 된 생성자를 호출하는 데 사용하고있다. – ChadM

+0

@Chad : 나는 'StoreScores' 기능을 의미했습니다. :) – Xeo

2

사용자 정의 소멸자가 있지만 복사 생성자 또는 할당 연산자가 없습니다. 어떤 숙제가 제대로 작동하지 않을지라도 하나의 버퍼가 누수되고 다른 버퍼가 두 번 누출되지 않습니다.

Rule of Three을 따르십시오. 또는 이미 디버그 된 컨테이너 (예 : std::vector)를 사용하는 것이 더 좋습니다.

관련 문제