gpt4 book ai didi

c++ - 在循环中使用 strtof 解析字符缓冲区中的数字

转载 作者:行者123 更新时间:2023-11-28 05:18:35 31 4
gpt4 key购买 nike

我有一个关于分配和释放内存的问题。

我想循环读取一个char buffer,并将float值保存到一个vector中。我通过读取 fstream 获取缓冲区。

但我的方法在最后删除缓冲区时总是崩溃。

我在循环期间更改缓冲区是否有问题?有人知道如何解决这个问题吗?

我感谢每一个提示!

char* buffer1 = new char[size]; // the size is given
char* buffer2 = NULL;

fileStream.read(buffer1,size);

while(true)
{
// read double from buffer
// and get pointer to the new buffer -> buffer2
double tempDouble = strtod(buffer1, &buffer2);

// If nothing has been read (buffer stays the same) -> break
if (buffer1 == buffer2)
break;
else // change the buffer to read the next double during the next interation step
buffer1= buffer2;

// collect the doubles
collectedDoubles.push_back(tempDouble);

// if all numbers are read -> break
if (++doubleCount == numDoubles) // termination condition
break;
}

// delete the allocated buffer
delete[] buffer1;

// do I have th delete the 2nd buffer too?
// delete[] buffer2;

最佳答案

  1. 根据 strtod 的文档:

    The functions sets the pointer pointed to by str_end to point to the character past the last character interpreted. If str_end is NULL, it is ignored.

    所以你的指针 buffer2 仍然是 NULL 并且在你执行 buffer1= buffer2; - buffer1 现在也是是 NULL(顺便说一句,这里是内存泄漏,因为数据丢失了)。

  2. do I have th delete the 2nd buffer too?

    在这种情况下 - 不,因为删除 NULL 指针是空操作。

解决方案:

看一下文档中为strtod函数提供的示例,根据您的代码,这里是类似的:

char* buffer1 = new char[size];
char* buffer2; // note no NULL here !
char* p = buffer1; // we'll modify this in loop

for (double tempDouble = std::strtod(p, &buffer2); p != buffer2; tempDouble = std::strtod(p, &buffer2))
{
p = buffer2;
if (errno == ERANGE){ // check if some error occured during attempt to convertion
std::cout << "range error\n";
errno = 0;
}

collectedDoubles.push_back(tempDouble);

if (++doubleCount == numDoubles) // termination condition
break;
}

delete[] buffer1;

编辑 1:看看 @JerryCoffin 在对您的问题的评论中建议的优雅且非常“类似 C++”的解决方案。

关于c++ - 在循环中使用 strtof 解析字符缓冲区中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42028184/

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