在TXT文件阅读矩阵并将其存储在二维数组 [英] read matrix in txt file and store it in array 2D
问题描述
我一直想在一个txt文件中的矩阵输入存储阵列中,但它告诉我这一点:这是code
I've been trying to store a matrix input in a txt file in a array but it show me this: this is the code
#include <stdio.h>
int main()
{
int c, i, j, row, col, nl, cr;
row = col = nl = cr = 0;
FILE *fp = fopen("g.txt", "r");
// Figure out how many rows and columns the text file has
while ((c = getc(fp)) != EOF)
{
if (c == '\n')
nl++;
if (c == '\r')
cr++;
col++;
if (c == '\n')
row++;
putchar(c);
}
col = (col - (nl + cr));
col = (int) (col/row);
// printf("\nnumber of rows is %d\n", row);
// read letters into array
char array[row][col];
if ( fp )
{
for ( ;; )
{
c = getc(fp);
if ( c == EOF )
{
break;
}
if ( c != '\n' && c != '\r' )
{
array[i][j] = c;
if ( ++j >= col )
{
j = 0;
if ( ++i >= row )
{
break;
}
}
}
}
fclose(fp);
}
for ( i = 0; i < row; i++ )
{
for ( j = 0; j < col; j++ )
{
putchar( array[i][j]);
}
putchar('\n');
}
return 0;
}
somone have any idea please? exemple of the txt file :
255 50 9 50 1 50 50 1
50 255 50 50 50 50 50 50
50 50 255 50 50 50 50 50
8 50 50 255 50 50 50 50
50 50 50 50 255 50 50 50
50 50 50 50 50 255 50 50
1 50 50 50 50 50 255 50
2 50 50 50 50 50 50 255
我的计划告诉我这一点:
my program show me this:
255 50 9 50 1 50 50 1
50 255 50 50 50 50 50 50
50 50 255 50 50 50 50 50
8 50 50 255 50 50 50 50
50 50 50 50 255 50 50 50
50 50 50 50 50 255 50 50
1 50 50 50 50 50 255 50
2 50 50 50 50 50 50 255 $■( 1gÍuáþ09■ ı¤ıu"ÒávD ê$[
► ð²( ♥ l ► ■
ê$[ ♥ l ²( O»ƒv[ 4■( Qõá
v♥ #õáv┬²║Oÿ|®v ñ|®ve┬ív
■( x■( ÿ|®v Ó²⌂ @■( áƒv╚♀[ L
■( w¯ƒv‼ ê■( I┴ávÿ|®v↓┴áv~²║O
Ó²⌂ \■( ■ ─ ( e┬ívÍ┬29►☺
输入文件显示它的好的,但问题是阵列输出我不undrestand为什么它显示此caracters
for the input file it show the good one ,but the problem is for the array output i don't undrestand why it show me this caracters
推荐答案
迈克尔的评论是正确的,我会感到惊讶,如果连编译。你需要动态分配阵列,像这样:
Michael's comment is correct, I'd be surprised if that even compiles. You'll need to allocate your array dynamically, like so:
char **array = malloc(sizeof(char *) * row)
和每一行,如:
数组[C] =的malloc(sizeof的(char)的* COL)
您必须释放每一行和每一阵列免费的。
You'll have to free each row and the array with free as well.
它也像你试图读取并存储整数值。请记住,当你得到这个工作,你仍然必须转换为字符值,如果是这样的话。
It also looks like you are trying read and store integer values. Keep in mind when you do get this working you'll still have to convert the character values if that is the case.
这篇关于在TXT文件阅读矩阵并将其存储在二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!