[英]How do I read a text file image and save it to an array?
我必须编写一个程序来读取文本二进制图像1和0,然后根据用户的选择对该图像执行各种操作。 我相信我对大多数程序都很好,我能够读取文件并显示它。 为了继续,我需要将图像保存到2D数组中,这就是我坚持的方法。
以下是我整个程序的一小部分示例,其余部分目前都可以正常运行,这是我想找出的一点,但是在继续搜索和观看视频后,我一生都无法弄清楚这一点或我打算去哪里错误。
#define N 50
int imageArray [N][N];
int row, col;
int value;
char filename[30];
FILE *ptr_file;
printf("Enter the full name of the input file: ");
scanf("%s", filename);
ptr_file = fopen(filename, "r");
for(row = 0; row < N; row++){
for(col = 0; col < N; col++){
fscanf(ptr_file, "%d", &value);
imageArray[row][col] = value;
}
}
for(row = 0; row < N; row++){
for(col = 0; col < N; col++){
printf("%d", imageArray[N][N]);
}
printf("\n");
}
我尝试保存到2D阵列的图像均为50x50,包含在txt文件中。
上面的代码当前输出全0。 图像的背景由0组成,而图像本身由1组成。
以下是我要保存到阵列的超小型版本 ,请将其想象为50x50! 由于某种原因,我无法将完整图像粘贴到此处,因为它重新格式化了。 它应该给一个想法。
0000000
0001000
0011100
0111110
0011100
0001000
0000000
在此先感谢您阅读本文!
您的代码有两个问题。
正如Mike P所说,您应在fscanf()中使用“%1d”,否则每个fscanf()调用将读取整行,因为它将继续读取直到带有“%d”的第一组数字字符的末尾。
您的打印循环正在打印imageArray[N][N]
而不是imageArray[row][col]
。
实施了这两个修复程序后,我的代码可以按预期运行。
int imageArray [N][N];
int row, col;
int value;
char filename[30];
FILE *ptr_file;
printf("Enter the full name of the input file: ");
scanf("%s", filename);
ptr_file = fopen(filename, "r");
for(row = 0; row < N; row++){
for(col = 0; col < N; col++){
fscanf(ptr_file, "%1d", &value);
imageArray[row][col] = value;
printf("%d %d\n", row, col);
}
}
for(row = 0; row < N; row++){
for(col = 0; col < N; col++){
printf("%d", imageArray[row][col]);
}
printf("\n");
}
作为附加说明,您应该检查fscanf()的返回值以确保调用成功。 如果您使用原始代码执行此操作,它将为您提供第一个错误的位置的良好提示。 它还可以用于检测无效的输入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.