Read complex numbers (a+bi) from text file in C++

前端 未结 4 1547
难免孤独
难免孤独 2021-01-15 09:03

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

相关标签:
4条回答
  • 2021-01-15 09:11
    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");
        }
    
    0 讨论(0)
  • 2021-01-15 09:26

    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 istreams.

    0 讨论(0)
  • 2021-01-15 09:26
    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.

    0 讨论(0)
  • 2021-01-15 09:33

    One option is to read separately the real and imaginary part in 2 ints, 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.

    0 讨论(0)
提交回复
热议问题