gpt4 book ai didi

c++ - 通过 fstream 读取文件时,损坏的数据存储在变量中……为什么?

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:04 24 4
gpt4 key购买 nike

当我输出如下所示的 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;
}

最佳答案

read() 不会在字符串末尾添加终止符。但是,当将 char* 转换为字符串时,它需要一个 nul 终止符。当你的缓冲区很短时你很幸运,最后有一个零,当它更长时有非零数据。

关于c++ - 通过 fstream 读取文件时,损坏的数据存储在变量中……为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12032822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com