我正在研究一个C项目,该项目要求我构建一个动态数组,并使用fscanf在文本文件中用一些字符填充它,同时跳过其他字符。
文本文件看起来像这样:
4
[* * 1 *]
[3 * 6 *]
[* * * *]
[2 * * 1]
第一个数字4是块的尺寸(始终为正方形)。基本上,每个'*'或数字代表数组中的一个元素。数组为1d,大小为* s或数字的总数。因此,在此示例中,数组大小为16。
无论是否有'*',我都需要用0填充数组。在此示例中,我的数组需要为[0,0,1,0,3,0,6,0,0, 0,0,0,2,0,0,1]
到目前为止,我的代码:
int size;
FILE *file_in;
file_in = fopen(name, "r");
if(!file_in) printf("File was not opened".);
fscanf(file_in, "%d", &size)
printf("the size of the block is %d x %d" , size, size);
p = (int *) malloc (size*size*(sizeof(int));
char temp;
fscanf(file_in, "%*c%*c"); //skip the first bracket and space
fscanf(file_in, "%c" , temp); //store first * in temp
if (if temp == '*') p[0] = 0;
printf("the first element is %d", p[0]);
我最终需要将代码的最后一部分放在循环中,以读取整个文件。当我运行此代码时,唯一打印出的内容是“块的大小为4 * 4”,除此之外没有其他内容。这使我认为我没有正确设置动态数组或正确使用malloc。或者我没有正确使用fscanf来读取文件。
有人能指出我正确的方向吗?另外,我知道打印循环还不正确。现在,我只是想让数组的任何部分正常工作。