C++ 读取多个文件时出现分段错误
我有下面这个程序,它从用户那里获取文件的数量,然后是文件名,并将文件的内容读入优先级队列。当我执行程序时,在我输入第一个文件名后,它给出了分段错误C++ 读取多个文件时出现分段错误,c++,C++,我有下面这个程序,它从用户那里获取文件的数量,然后是文件名,并将文件的内容读入优先级队列。当我执行程序时,在我输入第一个文件名后,它给出了分段错误 #include <cstdlib> #include <ctime> #include <functional> #include <iostream> #include <queue> #include <fstream> using namespace std; int
#include <cstdlib>
#include <ctime>
#include <functional>
#include <iostream>
#include <queue>
#include <fstream>
using namespace std;
int main() {
char *filename;
int fnum;
cout<<"Number of files:"<<endl;
cin>>fnum;
int i;
priority_queue<int, vector<int>, greater<int> > pqi;
for(i = 0; i<fnum;i++){
cout <<"Enter Filename:"<<endl;
cin>>filename;
ifstream inFile(filename);
long n;
while(!inFile.eof()){
inFile >> n;
pqi.push(n);
}
inFile.close();
inFile.clear();
}
while(!pqi.empty()) {
cout << pqi.top() << ' ';
pqi.pop();
}
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
字符*文件名;
内特fnum;
不能在你的代码中
char *filename;
然后你用
cin>>filename;
您没有为文件名分配任何空间,因此输入被写入一些未定义的内存中。可以将文件名
定义为字符数组,也可以使用std::string问题在于字符*
定义。您只需定义一个指针,而不向其分配任何内存。您必须分配内存使用new
关键字将y添加到它:
char *filename = new char[256];
//... rest of your code ...
//When you no longer need filename (usually at the end of the code)
//you have to free the memory used by it manually:
delete[] filename;
在这种简单的情况下,还可以使用静态数组:
char filename[256];
//No need to delete[] anything in this way.
上述两种方法都为文件名
分配了固定数量的内存,这意味着如果用户在上述示例中输入的文件名超过256字节,我们会遇到缓冲区溢出。您可以使用字符串
类型,它会自动为您进行内存管理,并且易于使用:
#include <string>
string filename;
cin >> filename;
#包括
字符串文件名;
cin>>文件名;
我可以建议编辑帖子并修复代码的缩进吗?你试过调试器了吗?如果这是作业,你必须明确地标记它作业
。不,这不是作业,我正在准备期末考试,这是我在过去的论文中遇到的问题。我意识到我的愚蠢,我一定是工作过度了。谢谢你的帮助帮助侯赛因。你可能是指缓冲区溢出而不是运行不足。