当我输出下面看到的 InitialSeedFinder 函数的返回值(也就是存储在种子变量中的值)时,我得到了一些随机的 ascii 字符,这些字符破坏了预期的字符串值。仅当缓冲区超过 2 个字符时才会发生这种情况(即,它适用于 order 变量小于 3 时)。
在下面的代码中看到的while循环中引入了这个错误......
有人可以解释为什么会这样吗?它与 read() 函数的工作方式有关吗?
string InitialSeedFinder(int order, string fileName){
string seed;
ifstream inputStream;
Map<string, int> frequencyMap;
inputStream.open(fileName.c_str());
int offset = 0;
inputStream.clear();
char* buffer = new char [order];
//get all k char sequence
while (inputStream.get() != EOF) {
inputStream.seekg(offset);
inputStream.read(buffer, order);
string key(buffer);
if (frequencyMap.containsKey(key)) {
frequencyMap[key] = frequencyMap[key] + 1;
}
else {
frequencyMap.put(key, 1);
}
offset++;
}
inputStream.close();
//go through and find the most frequent key
int greatestFrequency = 0;
int frequency = 0;
foreach(string key in frequencyMap)
{
frequency = frequencyMap[key];
if (frequency > greatestFrequency) {
greatestFrequency = frequencyMap[key];
seed = key;
}
}
return seed;
}