0

I'm trying to read an array from a file and then to assign these values to another array. I get a lot of zeros and really big numbers.

I've tried different specifiers but they are still the same. when there is no assignment and only one array is printed, there is no such a problem

int n;                   
FILE * fo; 
fo = fopen("f1.txt","r");
double complex mas[8];
double complex y[8];
int N = 0;
while (!feof(fo)) {
    fscanf(fo, "%lf", &mas[N]);
    printf("%lf  ", mas[N]);
    N++;
    printf("%d ", N);
}
fclose(fo);
printf("\n      N=%d\n", N);
for(n=0; n<N; n++)               
{
    y[n] = mas[n];
    printf("%f  %f\n", y[n], mas[n]);
}

looks like the values are being assigned but 1st array can't be printed enter image description here

Mayur Karmur
  • 2,119
  • 14
  • 35
pirateniw
  • 19
  • 3
  • 4
    Read [Why is “while (!feof(file))” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – Achal Jun 04 '19 at 04:45
  • 2
    Instead of `feof()` check the return value of `fscanf()`. For e.g `while (fscanf(fo, "%lf", &mas[N]) == 1) { }`. Also this works only if file having not more than `8` floating point numbers as you declare `mas[8]`. – Achal Jun 04 '19 at 04:46
  • 1
    while printing `y[n]` and `mas[n]` use `%lf` instead of `%f`. It should be `printf("%lf %lf\n", y[n], mas[n]);` Also do check the return value of `fopen()`. – Achal Jun 04 '19 at 04:48
  • 1
    @Achal `%f` and `%lf` are equivalent in `printf` (and both wrong for printing a `complex`) – M.M Jun 04 '19 at 05:10
  • still the same with %lf or %f – pirateniw Jun 04 '19 at 05:13
  • https://stackoverflow.com/questions/4099433/c-complex-number-and-printf – M.M Jun 04 '19 at 05:23
  • printf("%f%+fi %f%+fi\n", creal(y[n]), cimag(y[n]), creal(mas[n]), cimag(mas[n])); not it shows values of the right array on the screen, but there is stil this big number in 2 positions which appears to be img part – pirateniw Jun 04 '19 at 05:33

1 Answers1

2

There is no way to read a complex number directly

// read a double (%lf) into a complex is wrong
fscanf(fo, "%lf", &mas[N]);

You need to read each part separately, (assuming file contents have format "3.14159-2.71828i") maybe with

// read a complex parts
double r, c;
if (fscanf(fo, "%lf%lfi", &r, &c) != 2) /* error */;
// join the parts
mas[N] = r + c*I;
pmg
  • 106,608
  • 13
  • 126
  • 198