So, basically, I have to build a simple complex number calculator using C. However, both input and output have to be on string form. Keep in mind complex.h is not allowed, that's why a simple struct for the real and imaginary parts are needed.
For example, the string "-3.2+2.4i" would have to become:
a.real = -3.2;
a.img = 2.4;
And then back to string form after some sort of calculation was completed, which likely is way easier since all you need to do is convert it back using gcvt() and merge them both with strcat().
I have tried using strtok to split them but it was such a headache and it failed to work almost every time. It would be possible if both parts were always positive but the '+' and '-' signs were making everything a mess.
struct complex {
double real, img;
};
int main() {
struct complex a, b, c;
//calculator itself would be here
}
struct convertNumber() {
//conversion would happen here. Can I return both the real and imaginary parts at once with just this one fuction?
}
Use strtod
. It will parse the real part from the string and set a pointer to the first character after the real part. Then you can call strtod
again with that pointer to parse the imaginary part.
Here is an extremely simple (slightly unsafe) example:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
if (argc != 2) {
return 1;
}
char* startptr = argv[1];
char* endptr = NULL;
double real = strtod(startptr, &endptr);
if (startptr == endptr) {
return 1;
}
startptr = endptr;
endptr = NULL;
double imag = strtod(startptr, &endptr);
if (startptr == endptr) {
return 1;
}
if (*endptr != 'i') {
return 1;
}
printf("%f + %fi\n", real, imag);
return 0;
}