C++ 关于';std::bad#u alloc';
我读过其他的帖子,但没有一篇对我有帮助, 此代码没有错误,但仍然存在错误分配错误C++ 关于';std::bad#u alloc';,c++,C++,我读过其他的帖子,但没有一篇对我有帮助, 此代码没有错误,但仍然存在错误分配错误 #include <iostream> #include <fstream> using namespace std; int main() { char super[25]; char name[25],last_name[25]; int length; char *sym = "#"; char *buffer; ofstream
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char super[25];
char name[25],last_name[25];
int length;
char *sym = "#";
char *buffer;
ofstream outfile;
outfile.open("farses.dat",ios::app);
cout << "Writing to the file" << endl;
cout << "Enter your First Name: ";
cin >> name;
outfile << *sym;
outfile << name << endl;
cout << "Enter your Last Name: ";
cin >> last_name;
outfile << *sym;
outfile << last_name << endl;
cout << "Enter The Sentence : ";
cin.getline(super,25);
outfile << super << endl;
outfile.close();
ifstream infile;
infile.open("frases.dat");
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0,ios::beg);
buffer = new char[length];
infile.read(buffer , length);
cout << "\n\nReading from file \n\n" << endl;
cout << buffer << endl;
infile.close();
return 0;
}
#包括
#包括
使用名称空间std;
int main()
{
charsuper[25];
字符名[25],姓氏[25];
整数长度;
char*sym=“#”;
字符*缓冲区;
出流孔的直径;
outfile.open(“farses.dat”,ios::app);
根据经验法则,不要自欺欺人地认为你的代码没有错误。尤其是当你明显地犯了错误时。这种心态会让你找不到错误,因为你看到的一切都是正确的
您从未检查流是否已打开,并且在ofstream中输入了错误的文件名
发生的情况是,您将数据写入一个文件名farses.dat
,然后尝试打开一个名为frases.dat
(我假设它是正确的名称,意思是句子)的文件。
您正在获取一个不存在的文件的光标位置,但它失败了,因此函数返回-1。这是分配缓冲区之前的长度值。
当您分配缓冲区时,您会得到一个错误的alloc异常(错误的数组长度)
检查文件是否已打开,至少可以节省一些调试时间。
像这样的,
ifstream infile;
infile.open("frases.dat");
if ( infile.is_open() ) {
// File is open, do stuff (...)
if ( length <= 0 ) {
// Empty file / error, don't create buffer!!!
}
// (...)
infile.close();
}
else {
// Couldn't open file
}
ifstream-infle;
填充开放式(“frases.dat”);
if(infle.is_open()){
//文件已打开,请执行操作(…)
如果(长度)使缓冲区大小变大。你的句子明显大于25个字符。请尝试较小的句子或较大的缓冲区,如80。lol它甚至不允许我写句子lol…异常在“输入句子”后抛出语句有错误我的意思是说有语法错误..和thnx..在重命名文件后它工作了..没有语法错误意味着什么。还有其他类型的错误,这些只是容易捕获的错误。