【问题标题】:C++ text file editor crashes on file edit [closed]C ++文本文件编辑器在文件编辑时崩溃[关闭]
【发布时间】:2014-11-07 16:12:01
【问题描述】:

让我先说我是 C++ 新手,来自 Java,想学习新语言。

我使用 ofstream 通过循环遍历数组将数组写入文本文件,如下所示。

当我在 Notepad++ 或 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;
}

调用下面函数的函数

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);


}

将数组写入文件的函数

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;

}

【问题讨论】:

  • 文本编辑器本身崩溃了?两个都?这很奇怪。
  • for(int i=0; i&lt;=arrSize; i++){ 你确定&lt;=吗?

标签: c++ file runtime-error ofstream


【解决方案1】:

saveVocabSet 中,您正在越界访问数组

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

数组索引应该从 0 到 arrSize-1

【讨论】:

  • 做到了!不知道为什么这会导致记事本中出现运行时错误,除非终止的程序仍然打开文件,因为它从未离开循环。谢谢,一旦stackoverflow允许我接受答案。
  • @AhellHound:最好删除它,因为它是一个简单的错字。这对其他人没有帮助。
  • @LightnessRacesinOrbit 不会让我删除它。我会为版主举报。
猜你喜欢
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多