当我输出下面看到的InitialSeedFinder函数的返回值(也就是存储在种子变量中的值)时,我得到一些随机的ascii字符,它会破坏预期的字符串值。只有当缓冲区更多2个字符时才会发生这种情况(即,当订单变量小于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;
}
答案 0 :(得分:1)
read()不会在末尾添加终结符。但是,当将char *转换为字符串时,它需要一个nul终止符。当你的缓冲区很短时,你很幸运,最后有一个零,当它的时间更长时,数据非零。