I am unable to read imaginary data from text file. Here is my .txt file
abc.txt
0.2e-3 0.3*I 0.1 0.1*I
0.3 0.1*I 0.1 0.4*I
I want to read this data into a matrix and print it.
I found the solutions using C here and here. I don't know how to do the same in C.
I am able to read decimal and integer data in .txt and print them.
I am also able to print imaginary data initialized at the declaration, using complex.h
header. This is the program I have writtern
#include<stdio.h>
#include<stdlib.h>
#include<complex.h>
#include<math.h>
int M,N,i,j,k,l,p,q;
int b[2];
int main(void)
{
FILE* ptr = fopen("abc.txt", "r");
if (ptr == NULL) {
printf("no such file.");
return 0;
}
long double d=0.2e-3 0.3*I;
long double c=0.0000000600415046630252;
double matrixA[2][2];
for(i=0;i<2; i )
for(j=0;j<2; j )
fscanf(ptr,"%lf i%lf\n", creal(&matrixA[i][j]), cimag(&matrixA[i][j]));
//fscanf(ptr, "%lf", &matrixA[i][j]) for reading non-imainary data, It worked.
for(i=0;i<2; i )
for(j=0;j<2; j )
printf("%f i%f\n", creal(matrixA[i][j]), cimag(matrixA[i][j]));
//printf("%lf\n", matrixA[i][j]); for printing non-imainary data, It worked.
printf("%f i%f\n", creal(d), cimag(d));
printf("%Lg\n",c);
fclose(ptr);
return 0;
}
But I want to read it from the text, because I have an array of larger size, which I can't initialize at declaration, because of it's size.
CodePudding user response:
There are two main issues with your code:
You need to add
complex
to the variables that hold complex values.scanf()
needs pointers to objects to store scanned values in them. Butcreal()
returns a value, copied from its argument's contents. It is neither a pointer, nor could you get the address of the according part of the complex argument.Therefore, you need to provide temporary objects to
scanf()
, which receive the scanned values. After successfully scanning, these values are combined to a complex value and assigned to the indexed matrix cell.
Minor issues not contributing to the core problem are:
The given source is "augmented" with unneeded
#include
s, unused variables, global variables, and experiments with constants. I removed them all to see the real thing.The specifier
"%f"
(as many others) letsscanf()
skip whitespace like blanks, tabs, newlines, and so on. Providing a"\n"
mostly does more harm than one would expect.I kept the
"*I"
to check the correct format. However, an error will only be found on the next call ofscanf()
, when it cannot scan the next number.You need to check the return value of
scanf()
, always! It returns the number of conversion that were successful.It is common and good habit to let the compiler calculate the number of elements in an array. Divide the total size by an element's size.
Oh, and
sizeof
is an operator, not a function.It is also best to return symbolic values to the caller, instead of magic numbers. Fortunately the standard library defines these
EXIT_...
macros.The signs are correctly handled by
scanf()
already. There is no need to tell it more. But for a nice output withprintf()
you use the" "
as a flag to always output a sign.Since the sign is now placed directly before the number, I moved the multiplication by
I
(you can change it to lower case, if you want) to the back of the imaginary part. This matches also the input format.Error output is done via
stderr
instead ofstdout
. For example, this enables you to redirect the standard output to a pipe of file, without missing potential errors. You can also redirect errors somewhere else. And it is a well-known and appreciated standard.
This is a possible solution:
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
int main(void)
{
FILE* ptr = fopen("abc.txt", "r");
if (ptr == NULL) {
perror("\"abc.txt\"");
return EXIT_FAILURE;
}
double complex matrixA[2][2];
for (size_t i = 0; i < sizeof matrixA / sizeof matrixA[0]; i )
for (size_t j = 0; j < sizeof matrixA[0] / sizeof matrixA[0][0]; j ) {
double real;
double imag;
if (fscanf(ptr, "%lf%lf*I", &real, &imag) != 2) {
fclose(ptr);
fprintf(stderr, "Wrong input format\n");
return EXIT_FAILURE;
}
matrixA[i][j] = real imag * I;
}
fclose(ptr);
for (size_t i = 0; i < sizeof matrixA / sizeof matrixA[0]; i )
for (size_t j = 0; j < sizeof matrixA[0] / sizeof matrixA[0][0]; j )
printf("% f% f*I\n", creal(matrixA[i][j]), cimag(matrixA[i][j]));
return EXIT_SUCCESS;
}
CodePudding user response:
Here's a simple solution using scanf()
and the format shown in the examples.
It writes the values in the same format that it reads them — the output can be scanned by the program as input.
/* SO 7438-4793 */
#include <stdio.h>
static int read_complex(FILE *fp, double *r, double *i)
{
int offset = 0;
char sign[2];
if (fscanf(fp, "%lg%[- ]%lg*%*[iI]%n", r, sign, i, &offset) != 3 || offset == 0)
return EOF;
if (sign[0] == '-')
*i = -*i;
return 0;
}
int main(void)
{
double r;
double i;
while (read_complex(stdin, &r, &i) == 0)
printf("%g% g*I\n", r, i);
return 0;
}
Sample input:
0.2e-3 0.3*I 0.1 0.1*I
0.3 0.1*I 0.1 0.4*I
-1.2-3.6*I -6.02214076e23-6.62607015E-34*I
Output from sample input:
0.0002 0.3*I
0.1 0.1*I
0.3 0.1*I
0.1 0.4*I
-1.2-3.6*I
-6.02214e 23-6.62607e-34*I
The numbers at the end with large exponents are Avogadro's Number and the Planck Constant.
The format is about as stringent are you can make it with scanf()
, but, although it requires a sign (
or -
) between the real and imaginary parts and requires the *
and I
to be immediately after the imaginary part (and the conversion will fail if the *I
is missing), and accepts either i
or I
to indicate the imaginary value:
- It doesn't stop the imaginary number having a second sign (so it will read a value such as "
-6 -4*I
"). - It doesn't stop there being white space after the mandatory sign (so it will read a value such as "
-6 24*I
". - It doesn't stop the real part being on one line and the imaginary part on the next line.
- It won't handle either a pure-real number or a pure-imaginary number properly.
The scanf()
functions are very flexible about white space, and it is very hard to prevent them from accepting white space. It would require a custom parser to prevent unwanted spaces. You could do that by reading the numbers and the markers separately, as strings, and then verifying that there's no space and so on. That might be the best way to handle it. You'd use sscanf()
to convert the string read after ensuring there's no embedded white space yet the format is correct.