如何修复ifstream的seg错误核心转储错误
How to fix seg fault core dumped error for ifstream
输入文件
9
2 8
0 6
8 5
2 4
3 1
2 3
4 1
6 1
2 6
7 5
1 7
代码
#include<iostream>
#include<fstream>
using namespace std;
int main(void)
{
ifstream in;
char infile[40];
int c, u, v;
cout << "Please enter the input data file name(NO SPACES): ";
cin >> infile;
in.open(infile);
while(in.fail()) {
cout << "Please enter a CORRECT input data file name(NO SPACES): ";
cin >> infile;
in.open(infile);
}
//adj matrix
c = in.get();
int array[c-1][c-1];
for(int i=0; i<c; i++) {
for(int j=0; j<c; j++) {
array[i][j] = 0;
}
}
while(!in.eof()) {
u = in.get();
v = in.get();
array[u][v] = 1;
}
cout << c << endl;
for(int i=0;i<c;i++) {
cout << i << " ";
for(int j=0;j<c;j++){
cout << array[i][j] << " ";
}
cout << endl;
}
in.close();
return 0;
}
输出应该是什么样子
9
0 0 0 0 0 0 0 1 0 0
1 0 0 0 0 0 0 0 1 0
2 0 0 0 1 1 0 1 0 1
3 0 1 0 0 0 0 0 0 0
4 0 1 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0 0
6 0 1 0 0 0 0 0 0 0
7 0 0 0 0 0 1 0 0 0
8 0 0 0 0 0 1 0 0 0
当提示输入文件名时,如果我输入了不正确的文件名,它将继续提示我输入正确的输入文件,但当输入正确的文件名称时,我会得到"Segmentation fault(core dumped)"
我想要输出输入文件中给定的对应边的邻接矩阵。
std::basic_istream::get
将一次提取一个字符。因此'9'
与9
不同
假设您的文件实体正确且格式已知,请执行以下操作:
in >> c;
int array[c][c]; // Indices from 0 to c-1
for(int i=0; i<c; i++) {
for(int j=0; j<c; j++) {
array[i][j] = 0;
}
}
while( in >> u >> v) {
array[u][v] = 1;
}
也可以使用std::string
作为文件名,而不是字符数组。然后你可以使用
in.open( infile.c_str() ); // Pre C++11
或直接
in.open(infile); // with C++11
相关文章:
- C++映射分割错误(核心转储)
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 分段错误(核心转储)但无法弄清楚
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- qt C++命令行代码中的分段错误(核心转储)
- C++ atof - 分段错误(核心转储)
- 为什么我的代码包含错误分段错误(核心转储)?
- 运行编译的 a.out 后出现分段错误(核心转储)错误
- 运行我的代码时出现分段错误(核心转储)问题
- C++代码的分段错误(核心转储)
- 为什么我在执行main之前就出现分段错误(核心转储)
- OpenCV 分段错误(核心转储)在使用 cv::Mat::at 时
- 分段错误(核心转储) 重定向输入
- C++字符串中的分段错误(核心转储)
- 树实现给出分段错误(核心转储)错误 c++ 11