我想从文本文件中扫描一个矩阵,但看起来我编写的代码只适用于整数而不是浮点数。
#include <stdlib.h>
#include <stdio.h>
#define MAX 10000
int main(void) {
FILE *fp;
int i, j;
char s[MAX], ch;
if ((fp = fopen("3.txt", "r")) == NULL) {
printf("can not open this file!\n");
exit(1);
}
int row = 0;
while (fgets(s, MAX, fp) != NULL) //Count the line
row++;
rewind(fp); //
int col = 0; //Count the col
while (ch != '\n') //(ch=fgetc(fp))!='\n'&&(ch=fgetc(fp))!='\r'
{
if (ch == ' ') col++;
ch = fgetc(fp);
}
col++; //
double** jz = malloc(row * sizeof(double*)); //Allocate spaces
for (i = 0; i < row; i++)
jz[i] = malloc(col * sizeof(double));
rewind(fp);
for (i = 0; i < row; i++) //Read in the data
for (j = 0; j < col; j++) {
if (!fscanf(fp, "%lf", &jz[i][j])) {
break;
}
}
for (i = 0; i < row; i++) //Print the matrix
for (j = 0; j < col; j++) {
printf("%lf\t", jz[i][j]);
if (j + 1 == col) printf("\n");
}
fclose(fp);
}
例如,1 * 3矩阵 56.154 59.365 98.3333
似乎全部为 0.0000
我想知道我做错了什么。