程序未正确从文本文件中提取信息
Program isn't properly extracting info from text files
我需要一些帮助来弄清楚bug在哪里。我有两个文本文件,需要从中提取信息。
第一种是形式
- 单词1
- 单词2
- 单词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))
^^^^^^
这意味着你正在从成对距离文件中读取所有内容,然后第二个循环就没有什么可提取的了。
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 如何从也包含C++字母的文本文件中提取某些数字?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- JPG-如何从ICC配置文件部分APP2读取/提取数据
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 如何使用 WINAPI 和 C++ 提取可执行文件的文件描述?
- 查找并提取文件中的某个值
- 如何从txt文件c++中提取括号之间的数字
- 在Linux Mint 19下,从哪里提取wxWidgets的源代码(.cpp文件)用于步骤内部调试
- 如何将ASCII数字转换为从文件中提取的整数
- 帧提取 使用OpenCV的视频文件开头只有几秒钟
- 从 C++ 中的文件路径中提取文件名
- 将文本文件数据读入字符数组时提取运算符的歧义
- 从.o目标文件中提取函数的原始机器代码?
- 有谁知道ziplib是否能够在不实际提取所有文件的情况下验证zip库
- 是否可以为给定的静态库人为地诱导对象文件提取
- C++将.reg文件提取到注册表
- c++文件提取检查是否为int
- 使用文件提取操作符读取int或string