我试过了:
void read_grid_from_file( int** grid, const size_t row, const size_t column, FILE* inf ) {
size_t x, y;
for( x = 0; x < row; ++x ) {
for( y = 0; y < column; ++y ) {
fscanf( inf, "%d", &grid[x][y] );
printf( "%d ", grid[x][y] );
}
printf( "\n" );
}
}
int main( int argc, char *argv[] ) {
FILE* inf; // input file stream
FILE* outf; // output file stream
char pbm_name[20];
size_t row = 0;
size_t column = 0;
/*
if( argc != 3 ) {
prn_info( argv[0] );
exit( 1 );
}
*/
inf = fopen( "infile.txt" , "r" );
outf = fopen( "outfile.txt", "w" );
fgets( pbm_name, 20, inf );
fscanf( inf, "%d", &row );
fscanf( inf, "%d", &column );
int** grid = allocate_memory_for_grid( row, column );
read_grid_from_file( grid, row, column, inf );
show_grid( grid, row, column ); //for debugging
}
输入文件是:
P1
12 14
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
输出结果为:
1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 0 0
0 0 1 1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
Press any key to continue . . .
该矩阵来自何处?
答案 0 :(得分:4)
我猜你刚刚改变了你的行和列。输入文件中有12列和14行,而在代码中,您将行作为列和列读取为行。
答案 1 :(得分:1)
您已阅读row
,然后阅读column
。应该反之亦然,column
然后row
。
答案 2 :(得分:0)
对不起伙计们,我想我知道了,文本文件中的行和列被颠倒了!!
答案 3 :(得分:0)
您似乎正在阅读.pbm
文件。如果许可证适合您的目的,您可以考虑使用netpbm library。