Hi, I am writing a program to perform nodal analysis and I need complex input for phasors and impedances. I have declared the variable and I want to read its value from standard input:
Hovever the only way for it to accept a complex input is if I write it in the form:
complex <float> VoltageSource;
cout << "Enter voltage source value: " << endl;
cin >> source;
My question: is there any way to make it read "2 3" or "2+3i" to give me 2+3i? Is there a way to read only to the real or imaginary part of a given complex variable? VoltageSource.real and VoltageSource.imag give me an error, so I concluded that they are probably used for output only.
Allows for the first form "1.2 6.2" for instance. For the second form, read in a string and parse it.
int main(int argc, char** argv)
std::cin >> complex._Val >> complex._Val;
std::cout << complex << std::endl;
Is there a guarantee that the members are public? I couldn't find one, but I may be looking in the wrong place.
It's tempting to tell your users "write your input the right way darn it".
Silly code example because why not:
float x, y;
cin >> x >> y;
foo << "(" << x << "," << y << ")";
foo >> bob;
cout << bob;
Hmm you are correct in that i couldn't find a guarantee for them to be public, however temporary floats and using the constructor that takes two complex::value_type would serve the same purpose.
To set the real and imag parts just use operator= with a temporary std::complex where you have set real and imag to the value you either want to keep or to change.
std::complex overloads stream operators, so you should be able to do
std::cout << "Enter complex number: ";
std::cin >> complex_num;