When I use fprintf
, it actually saves the wrong content.
Usually fprintf
outputs what I want, but this time it's outputting seemingly irrelevant numbers, and I don't know what the problem is.
My Inputs & Expected output
1 2 3
4 5 6
7 8 9
Actual Output
3 0 4199352
1 11 0
9 0 2
I used a for
loop to output a two-dimensional array
My code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void filein(int x, int y) {
FILE *fin;
int s[x][y];
int i, j;
if ((fin = fopen("test.txt", "r")) == NULL) {
printf(" can't open");
}
else {
printf("opening...\n");
}
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
fscanf(fin, "%d", &s[i][j]);
}
fscanf(fin, "\n");
}
fclose(fin);
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d ", s[i][j]);
fflush(stdout);//输出
}
printf("\n");
}
}
void fileout(int x, int y) {
FILE *fout;
int s[x][y];
int i, j;
char outname[50];
printf("please input the name of output file (no include\".txt\"):\n");
fflush(stdout);
scanf("%s", outname);
strcat(outname, ".txt\0");
fout = fopen(outname,"w");
if (fout == NULL) {
printf("Error!");
fflush(stdout);
}
else {
printf("Writing....\n");
fflush(stdout);
}
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
fprintf(fout, "%d ", s[i][j]);
}
fprintf(fout,"\n");
}
fclose(fout);
}
int main() {
int x, y;
printf("what is m?\n");
fflush(stdout);
scanf("%d", &x);
printf("what is n?\n");
fflush(stdout);
scanf("%d", &y);
filein(x, y);
fileout(x, y);
printf("finish");
fflush(stdout);
return 0;
}