2014-10-22 41 views
0

输入文件如何解决赛格故障核心转储错误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 

当提示输入文件名时,如果输入错误的文件名,它将继续提示我输入正确的输入文件,但是当输入正确的文件名时,将出现“分段错误(核心转储)”

I要输出输入文件中给定的相应边的邻接矩阵。

+2

两件事情:使用的,而不是'char's阵列的'的std :: string',字符''9''不与整数'9'相同,从你的文件中读取类似'int foo; in >> foo;'。 – user657267 2014-10-22 05:02:00

+0

第三件事:[最小完整示例](http://stackoverflow.com/help/mcve)简化了一切。你可能会删除很多这样的代码,但仍然会出现相同的错误。 (它可能只是未定义的行为,将'9'与'9'混淆并将其用作索引。) – Beta 2014-10-22 05:06:44

+0

'int array [c-1] [c-1];'是无效的C++代码。你如何让你的代码编译? – 2014-10-22 05:18:27

回答

1

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 
+1

真实且正确,但segfault大概是由数组定义'int array [c-1] [c-1];'应该是'int array [c + 1] [c + 1];' – user1781290 2014-10-22 05:16:58

+0

@ user1781290是的,谢谢! – P0W 2014-10-22 05:18:35

+1

@ user1781290它应该是'int array [c] [c];'只有OP输入有0和8作为最小最大值。 – P0W 2014-10-22 05:20:07