我使用 VS 2010 作为我的 IDE,这段代码工作正常,直到 fgets 被作为 puts 参数调用的那一行。它可以很好地记录文件中的数字,但也会打印一些烦人的乱码。也许我在某个地方缺少一个\0 ,不知道。其他人在 mingw 或 gcc 等其他编译器上尝试过,效果很好。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a, n, i;
char str[512];
FILE *f;
printf("Insert array size: ");
scanf("%d", &n);
if(n <= 0)
{
printf("%d is not an allowed value!\n", n);
return 1;
}
a = (int*)malloc(n * sizeof(int));
if(a == NULL)
return 2;
putchar('\n');
f = fopen("myarray.txt", "r+");
if(f == NULL)
return 3;
for(i = 0; i < n; ++i)
{
printf("Insert %d. element of the array: ", i + 1);
scanf("%d", &a[i]);
fprintf(f, "%d ", a[i]);
}
putchar('\n');
puts(fgets(str, 512, f));
free(a);
fclose(f);
return 0;
}
最佳答案
关于C - fgets() 产生乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998734/