[英]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()無法預測下一次讀取是否有效。
哦,人們從哪里來的呢? 就像疾病!
如果我的目標是簡潔而不是表現,這就是我要做整個程序的方式。
// 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.