正在将字符串从文件读取到数组中

Reading strings from file into array

本文关键字:读取 数组 文件 字符串      更新时间:2023-10-16

嘿。我正在尝试从一个包含单词列表的文件中将字符串读取到数组中。这样我就可以检查字符串是否是一个真实的单词,如果它们存在于我的数组中。除了比较,我什么都能用。我的二进制搜索甚至忽略了有问题的单词。当它比较完全相同的两个单词时,它仍然返回false。我想问题可能出在我插入单词的方式上,因为string.compare((函数工作正常。这是代码。我希望得到一些帮助。谢谢

  ifstream dictFile;
  dictFile.open("dictionary.txt");
  if (!dictFile) // testing if file open
    {
      cout << "Error opening dictionary file" << endl;
    }
  int index = 0; // dictionary must progress start at line 1
  while(!dictFile.eof())
    {
      getline(dictFile,dictionary[index]);
      index++;
    }
  dictFile.close();

我做这件事的方式有什么明显的错误吗?

编辑这是比较代码以及

bool database::is_word(string word)
{
  int ii;
  int comp;
  int min = 0;
  int max = dictSize;
  // this will go into the dictionary and look for the word
  // it uses a binary search pattern
while (min<=max)
    {
      ii = (min+max)/2;
      comp = word.compare(dictionary[ii]);
      cout <<dictionary[ii];
      if (comp==0)
    {
      cout << word<< " is a word!" << endl;
      return 1;
    }
      else if (comp < 0)
    {
      max = ii-1;
    }
      else
    {
      min = ii+1;
      }
      }
 cout << word << " is NOT a word!" << endl;
  return 0;
}

不要再使用eof((函数了!您想要:

while( getline(dictFile,dictionary[index]) ) {
  index++;
}

(假设dictionary是合理的,但可能不是(,因为eof((无法预测下一次读取是否有效。

人们从哪里开始使用of((?这就像一种疾病!

如果我的目标是简洁而不是性能,我会这样做整个程序。

// read the dictionary 
vector<string> dictionary;
{
  ifstream dictionary_file("dictionary.txt");
  istream_iterator<string> begin(dictionary_file);
  istream_iterator<string> end;
  while( begin != end )
    dictionary.push_back( *begin++ );
  sort( dictionary.begin(), dictionary.end() );
}
// read the input file and test against the dictionary
{
  ifstream input_file("input.txt");
  istream_iterator<string> begin(input_file);
  istream_iterator<string> end;
  while( begin != end )
  {
    string input = *begin++;
    vector<string>::iterator it = lower_bound( dictionary.begin(), dictionary.end(), input );
    if( it != dictionary.end() && *it == input )
      cout << input << " found!" << endl;
    else
      cout << input << " not found!" << endl;
  }
}