using sstream with complex numbers

150 Views Asked by At

I am trying to read a list of complex numbers from a txt file given as:

3+5i
2-3i
11+22i

However when i use stringstream(oneline)>>real>>plusorminus>>im>>ichar; the real part is okay but the im part always shows up as 0. I tried to debug it by adding the cout<<im and no matter what I tried I'm always showed up as zero.

string oneline;
double real, im;
char sign, ichar;
    
// fin opens a text file that has complex numbers written in the form of a+bi
while (!fin.eof()) {
    getline(fin, oneline);
    real = 0; 
    im = 0; 
    plusorminus = '\0'; 
    ichar = '\0';
    stringstream(oneline) >> real >> plusorminus >> im >> ichar;
    cout << im; //this is showing as 0 no matter what while instead it should read the imaginary part. The real part is being read fine.

    switch (plusorminus) {
        case '-': 
            im = -im; 
            break;
        case 'i': 
            im = real; 
            real = 0; 
            break;
        case '\0': 
            im = 0; 
            break;
    }
0

There are 0 best solutions below