程序未正确从文本文件中提取信息

Program isn't properly extracting info from text files

本文关键字:文件 提取 信息 文本 程序      更新时间:2023-10-16

我需要一些帮助来弄清楚bug在哪里。我有两个文本文件,需要从中提取信息。

第一种是形式

  1. 单词1
  2. 单词2
  3. 单词3

等。

我只想把这些单词放进std::向量中。文本文件中有5000个单词。当我在代码中放入一行测试代码并运行它时,我发现它只有729个单词。

第二个文本文件的格式为

a a 0a b 5a c3

我想把它们放进一个std::映射中,它把成对的字符映射成整数。当我在代码中放入一小段测试行并运行它时,我发现它向映射中添加了零个元素。

以下是相关代码:

class AutoCorrector
{ 
public: 
AutoCorrector(std::ifstream&, std::ifstream&);
~AutoCorrector();
void suggest(std::string);
private: 
std::vector<std::string> wdvec;
std::map<std::pair<char,char>,int> kdmap;

};
AutoCorrector::AutoCorrector(std::ifstream& wdfile, std::ifstream& kdfile) 
{
/* Insert 5000 most commond English words into a vector. 
The file that is read was edit-copied copied from 
http://www.englishclub.com/vocabulary/common-words-5000.htm
and so the numberings must be ignored on each line in order
to properly extract the words.
*/
if (wdfile.is_open()) { 
std::string line;
while (std::getline(kdfile, line))
{
std::istringstream ss(line);
std::string nb, thisWord;
ss >> nb >> thisWord;
wdvec.push_back(thisWord);
}
// test --- 
std::cout << "wdvec size = " << wdvec.size() << std::endl;
// -------
}
else
{
throw("Was not able to open key distance file.n");
}   
/* Insert keyboard pairwise distances into a map.
The file that is read from must have lines of the form
a a 0
a b 5
a c 3
etcetera, 
indicating the distances between characters on a standard keyboard, 
all lower-case letters and the apostrophe for a total of 27x27=729
lines in the file.
*/
if (kdfile.is_open()) { 
std::string line;
while (std::getline(kdfile, line))
{
std::istringstream ss(line);
char c1, c2; 
int thisInt;
ss >> c1 >> c2 >> thisInt;
std::pair<char,char> thisPair(c1, c2);
kdmap.insert(std::pair<std::pair<char,char>, int> (thisPair, thisInt));
}
// test --
std::cout << "kdmap size  = " << kdmap.size() << std::endl;
// end test
}
else
{
throw("Was not able to open key distance file.n");
}

}

我们非常感谢StackOverflow C++纯粹主义者的任何帮助。我愿意接受关于如何简化和美化代码的建议。最终,我试图制作一个自动相关器,从5000个最常见的单词列表中提取一个单词并搜索最相似的单词。

27*27=729。因此,第一个向量的行数与第二个文件的行数相同。为什么?因为你是在读kdfile,而你本想读wdfile

while (std::getline(kdfile, line))
^^^^^^

这意味着你正在从成对距离文件中读取所有内容,然后第二个循环就没有什么可提取的了。