如何修复ifstream的seg错误核心转储错误

How to fix seg fault core dumped error for ifstream

本文关键字:错误 核心 转储 seg 何修复 ifstream      更新时间:2023-10-16

输入文件

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