使用ifstream c ++ 11

时间:2017-11-02 03:54:43

标签: c++ c++11 ifstream

我正在创建一个名为SpellChecker的对象,它可以纠正字符串中单词的拼写。

要检查单词是否拼写正确,如果没有更正,我有一个正确单词的文本文件(每行一个)。我还有一个拼写错误的单词的文本文件,它们的更正用标签分隔。

我的问题是在我的文本文件中阅读。我创建了一个if语句,以查看我的文件是否成功打开。但是,我相信我的文件应该是可读的,而不是。我试图找出为什么会发生这种情况。

这是我的SpellChecker构造函数:

SpellChecker::SpellChecker(string tempLanguage, string correctWordsFile,string wordCorectionsFile){

language=tempLanguage;

ifstream istream;

istream.open(correctWordsFile);

if(!istream.is_open()){
  cout << "Error opening " << correctWordsFile << endl;
}

int count=0;
string temp;

while(!istream.eof()){
  getline(istream,temp);
  correctWords[count] = temp;
  count++;

}

numCorrectWords = count;

istream.close();

istream.open(wordCorectionsFile);

if(!istream.is_open()){
  cout << "Error opening " << wordCorectionsFile << endl;
}

int j=0;
int i=0;
char temp2;

while(!istream.eof()){

  istream.get(temp2);

  if(temp2 == '\t'){
    j++;
  }
  else if(temp2 == '\n'){
    i++;
    j = 0;
  }
  else
    wordCorections[i][j] += temp2;
}

numwordCorrections = i;

istream.close();
}

这是我的main

int main(){
  SpellChecker spellCheck("English","CorectWords.txt","WordCorections.txt");
  spellCheck.viewCorrectWords();
  spellCheck.viewCorrectedWords();
  spellCheck.setEnd('~');
  spellCheck.setStart('~');
  cout << spellCheck.repair("I like to eat candy. It is greatt.");
}

终端返回:

"Error opening CorectWords.txt"

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

对库函数is_open()的调用返回false,这可能是由于众多原因之一 确保:
1.您使用了正确的数据文件名称 2.数据文件与程序的可执行文件位于同一文件夹中 任何以前阅读它的程序都已关闭它。

相关问题