正在将字符串从文件读取到数组中
Reading strings from file into array
嘿。我正在尝试从一个包含单词列表的文件中将字符串读取到数组中。这样我就可以检查字符串是否是一个真实的单词,如果它们存在于我的数组中。除了比较,我什么都能用。我的二进制搜索甚至忽略了有问题的单词。当它比较完全相同的两个单词时,它仍然返回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;
}
}
相关文章:
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- For 循环在尝试读取数组 c++ 时程序崩溃
- 从文件中读取数组没有给出正确的值?
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- C++:无法读取数组中的内容
- 读取数组的第一个元素还是第 4000 个元素更快?
- 为什么并行读取数组会导致内存泄漏?
- 读取数组中每个对象的所有键值对
- C++ 从指定范围内的文件中读取数组
- MPI_Get仅从共享内存区域读取数组的第一个元素
- 如何使用指针函数编写/读取数组
- 程序仅读取数组中 6 个值中的 4 个
- ARDUINO LCD:通过读取数组生成导航菜单
- 如何从 Arduino 库中读取数组
- 尝试创建一个读取数组并打印质数的程序
- 因为每个循环都读取数组错误
- 在 Linux 上使用 Getenv 在 C++ 中读取数组环境变量
- 如何在c++中读取数组中的输入文件
- 动态设置数组大小并从文本文件中读取数组值
- 从boost::p roperty_tree读取数组显示为空白