【发布时间】: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<=arrSize; i++){你确定<=吗?
标签: c++ file runtime-error ofstream