2011-04-26 84 views
1

嘿。我试图从包含单词列表的文件中将字符串读入数组。这是为了让我可以检查是否字符串是一个真正的单词是否存在于我的数组中。除了比较之外,我有一切工作。我的二进制搜索甚至传递了这个词。当它比较完全相同的两个单词时,它仍然返回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; 
} 
+0

Getline是否检索该单词以及该行末尾的\ n(返回)?如果是这样,比较可以认为这些词是不同的,因为它会像“词”!=“词\ n”loook。只是一个想法。 – Genzume 2011-04-26 16:34:54

+0

@Tyler getline()删除换行符。 – 2011-04-26 16:37:54

+0

@unapersson好的,很高兴知道。谢谢。 – Genzume 2011-04-26 16:39:00

回答

1

不是EOF()函数再次!你想:

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

(假设dictionary是什么明智的,它可能不是),因为EOF()不预测,如果下一个读会工作。

哪里有人从哪里拿起eof()的这个用法?这就像一种疾病!

+0

看到它的地方...我会立即做一个精神上的笔记,不要再次使用它。但是,此修复程序会产生相同的错误。 – Rusty 2011-04-26 16:44:22

+1

我更喜欢把它写成:'for(string line; getline(input,line);){...}'因为它比较习惯,可以对行内容进行后期处理,并且在各种容器类型中是统一的。 – 2011-04-26 17:53:10

+0

@Andre我不能说我认为它是惯用的 - 我期望for循环从一个已知值循环到另一个,而不是不确定。 – 2011-04-26 18:18:03

0

这就是我如何做整个程序,如果我的目标是简洁而不是表现。

// 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; 
    } 
} 
+0

使用'std :: set'可能会给你更好的性能,使意图更清晰,并简化它:'dictionary.find(word)!= dictionary.end()'比使用lower_bound ()'在矢量上! – 2011-04-26 17:57:16

+1

你说得对,std :: set会更清晰,但你错了,它会有更好的表现。 std :: set和一个已排序的std :: vector在搜索一个项目时应该具有完全相同的性能。 – bmcnett 2011-04-26 18:08:35