1
我在运行下面的代码时遇到问题。每次我设置了while循环到达.EOF()返回一个std :: bad_alloc的为什么我得到std :: bad_alloc错误
inFile.open(fileName, std::ios::in | std::ios::binary);
if (inFile.is_open())
{
while (!inFile.eof())
{
read(inFile, readIn);
vecMenu.push_back(readIn);
menu.push_back(readIn);
//count++;
}
std::cout << "File was loaded succesfully..." << std::endl;
inFile.close();
}
它运行很好,如果我设定预定的迭代次数,但是当我用EOF funtion失败。这里是读取功能的代码:
void read(std::fstream& file, std::string& str)
{
if (file.is_open())
{
unsigned len;
char *buf = nullptr;
file.read(reinterpret_cast<char *>(&len), sizeof(unsigned));
buf = new char[len + 1];
file.read(buf, len);
buf[len] = '\0';
str = buf;
std::cout << "Test: " << str << std::endl;
delete[] buf;
}
else
{
std::cout << "File was not accessible" << std::endl;
}
}
任何帮助,您可以提供非常感谢。 注:我没有提到vecMenu是类型为std ::的矢量 和菜单式的std ::的名单
请参阅这篇文章:为什么是的iostream :: EOF算错了一个循环条件中(http://stackoverflow.com/questions/ 5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Rakete1111
谢谢@ Rakete1111 – Akatosh
另外,为读取的每一行调用分配器会减慢程序的运行速度。最好使用非本地'std :: vector'并发出'resize()'调用,而不是每次发出'new/delete'调用。 – PaulMcKenzie