我在运行下面的代码时遇到问题。每次我设置 while 循环到达 .eof() 它返回一个 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 函数时失败。这是读取函数的代码:
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::vector 类型 菜单的类型是 std::list
最佳答案
我看到的主要问题是:
您正在使用
while (!inFile.eof())
来结束循环。参见 Why is iostream::eof inside a loop condition considered wrong? .在使用读入的变量之前,您没有检查对
ifstream::read
的调用是否成功。
我建议:
更改您的
read
版本以返回对ifstream
的引用。它应该返回作为输入的ifstream
。这使得在循环条件中调用read
成为可能。在使用前检查对
ifstream::read
的调用是否成功。将对
read
的调用放在while
语句的条件中。
std::ifstream& read(std::fstream& file, std::string& str)
{
if (file.is_open())
{
unsigned len;
char *buf = nullptr;
if !(file.read(reinterpret_cast<char *>(&len), sizeof(unsigned)))
{
return file;
}
buf = new char[len + 1];
if ( !file.read(buf, len) )
{
delete [] buf;
return file;
}
buf[len] = '\0';
str = buf;
std::cout << "Test: " << str << std::endl;
delete[] buf;
}
else
{
std::cout << "File was not accessible" << std::endl;
}
return file;
}
和
inFile.open(fileName, std::ios::in | std::ios::binary);
if (inFile.is_open())
{
std::cout << "File was loaded succesfully..." << std::endl;
while (read(inFile, readIn))
{
vecMenu.push_back(readIn);
menu.push_back(readIn);
//count++;
}
inFile.close();
}
关于c++ - 为什么我会收到 std::bad_alloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41420861/