[英]Program isn't properly extracting info from text files
我可以使用一些帮助找出错误所在。 我有2个文本文件需要提取信息。
首先是形式
等等
我只想将单词放入std :: vector中。 文本文件中有5000个单词。 当我在代码中放一个测试器行并运行它时,我看到它只有729个单词。
第二个文本文件的格式为
aa 0 ab 5 ac 3
诸如此类
我想将它们放入std :: map中,该映射将成对的字符映射为整数。 当我在代码中放一个测试器行并运行它时,我发现它向地图添加了零个元素。
以下是相关代码:
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
读取kdfile
时,您正在从kdfile
读取wdfile
。
while (std::getline(kdfile, line))
^^^^^^
这意味着您正在从成对距离文件中读取所有内容,然后第二个循环没有任何内容可提取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.