Agustin Luques Agustin Luques - 3 months ago 8
C Question

From a string "a ± bi" to number in C

I need to convert a string in the

a ± bi
form to an
int Real
and an
int Im
. And in the case that the string isn't in that form, print an error. I have an idea to convert the
a
to the int and also the
b
but I don't know what to do with de imaginary number if it is positive.

i.e.

0,034 - 1,2i

>a=0,034
>b=-1,2

0,25

>Error, you must write in "a±bi" form

3,234 + 34,43i

>a=3,234
>b=34,43


ps: I found this link but it is in C++ and I don't know what it is doing

EDIT: THE REAL NUMBER COULD HAVE A PLUS OR MINUS.

Answer

It is quite simple, the C-standard has all you need:

#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 100

// ALL CHECKS OMMITTED!

int main()
{
  double a, b;
  char buffer[BUFFER_SIZE];
  int count = 0;
  char c;
  char *endptr;

  while ((c = fgetc(stdin)) != EOF) {
    if (c == '\n') {
      // make a proper C-string out of it
      buffer[count] = '\0';
      // reset counter for the next number
      count = 0;
      // strtod() is intelligent enough to
      // stop at the end of the number
      a = strtod(buffer, &endptr);
      // endptr points to the end of the number
      // skip whitespace ("space" only)
      while (*endptr == ' ') {
        endptr++;
      }
      // skip the +/- in the middle
      endptr++;
      // strtod() skips leading space automatically
      b = strtod(endptr, NULL);
      printf("a = %g, b = %g\n", a, b);
    }
    // read all into a big buffer
    buffer[count++] = (char) c;
    if (count >= BUFFER_SIZE) {
      fprintf(stderr, "Usage: type in complex numbers in the form \"a + b\"\n");
      exit(EXIT_FAILURE);
    }
  }

  exit(EXIT_SUCCESS);
}

See? No need to worry.