2014-11-07 1 views
-4

저는 C++에 매우 익숙하며 Java에서 왔고 새로운 언어를 배우고 싶다고 말하면서 머리말을 붙이겠습니다.파일 편집시 C++ 텍스트 파일 편집기가 충돌 함

아래에서 볼 수 있듯이 ofstream을 사용하여 배열을 반복하면서 텍스트 파일에 배열을 작성했습니다.

파일을 메모장 + + 또는 Microsoft 메모장에서 열면 파일의 모든 항목이 표시되지만 런타임 오류로 인해 편집기가 작동하지 않습니다.

내 주요 기능

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

using namespace std; 

int main() { 

    //Prototyped functions 
    int getMenuOption(); 
    int printMenu(); 
    void beginNewVocabularySet(); 

    void printIntro(); 

    int option = getMenuOption(); 

    switch(option){ 

    case 2: beginNewVocabularySet(); 

    } 

    return 0; 
} 

saveVocabSet에서 파일

int saveVocabSet(string vocabArr[], int arrSize){ 

    ofstream vocabFile ("vocabList.txt"); 

    if (vocabFile.is_open()){ 

     for(int i=0; i<=arrSize; i++){ 

      vocabFile<< vocabArr[i] << "\n"; 

     } 

     vocabFile.close(); 

    }else { 

     cout << "Unable to open file"; 
     return 1; 
    } 

    return 0; 

} 
+1

arrSize에 텍스트 편집기에서 가야하나요? 둘 다? 그것은 매우 이상합니다. –

+0

'for (int i = 0; i <= arrSize; i ++) {'당신은'<='에 대해 확신합니까? –

답변

2

에 당신이 액세스하는을 배열을 기입 기능

void beginNewVocabularySet(){ 

    int vocabSize = 0; 

    cout << "Please enter the length of the vocabulary set\n"; 

    cin >> vocabSize; 

    string vocabArray[vocabSize]; 

    cout << "Please enter a word, then press enter to make the second entry.\n"; 

    for(int i=0; i < vocabSize; i++){ 

     cin >> vocabArray[i]; 
     cout << "Entry number " << i+1 << ". " << vocabArray[i] << "\n"; 

    } 

    saveVocabSet(vocabArray, vocabSize); 


} 

아래의 함수를 호출 기능 배열 범위 밖

for(int i=0; i <= arrSize; i++) 
//    ~~ should be i < arrSize or i <= arrSize-1 

배열 인덱스 자체가 충돌 0 -1

+0

그랬어! 그것이 결코 루프를 떠나지 않았기 때문에 종료 된 프로그램이 여전히 파일을 열어 두지 않았다면, 그것이 메모장에서 런타임 오류를 유발하는 이유는 확실치 않습니다. 감사합니다. stackoverflow를 사용하면 답변을 수락합니다. – Colby

+0

@AhellHound : 간단한 오타 였기 때문에 삭제하는 것이 가장 좋습니다. 이것은 다른 누구에게 도움이되지 않습니다. –

+0

@LightnessRacesinOrbit 삭제하지 않겠습니다. 사회자에게 깃발을 댈거야. – Colby