i want to read an array of complex numbers (in a+bi
form). There are several suggestions I found on the internet, however those methods only result the re
FILE *fp;
char line[80];
int a, b;
if ((fp = fopen("filename", "r") != NULL)
while (fgets(line, 80, fp) != NULL) {
if (sscanf(line, "%d + %di", &a, &b) == 2)
/* do something with a and b */
else
fprintf(stderr, "Not in a+bi form");
}
Your requirement (the format of input you seek) does not correspond to the method you are using to read it. The default streaming of a complex is the real and the imaginary part separated by spaces and in brackets - the sign between is not mandatory, and the trailing i
is not required.
The obvious way to parse for input you seek is to read the real part, read a character, check if the character is a signed (+
or -
) and ignore spaces, then read the imaginary part. That is trivial with istream
s.
int real[10] = { 0 };
int imaginary[10] = { 0 };
FILE *lpFile = fopen("filename" "rt"); // Open the file
for (int i = 0; i < 10; i++) {
fscanf(lpFile, "%d+%di", &real[i], &imaginary[i]); // Read data 10 times
}
fclose(lpFile); // Close the file
This example code will read 10 complex numbers from a file.
One option is to read separately the real and imaginary part in 2 int
s, and the sign into a char
, then emplace_back
into the complex vector, like
int re, im;
char sign;
while (stream >> re >> sign >> im)
{
vec.emplace_back(re, (sign == '-') ? -im : im);
}
Here sign
is a char
variable that "eats" up the sign.