-
Complex input
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:
Code:
complex <float> VoltageSource;
cout << "Enter voltage source value: " << endl;
cin >> source;
Hovever the only way for it to accept a complex input is if I write it in the form:
(real,imag).
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.
-
Code:
int main(int argc, char** argv)
{
std::complex<float> complex;
std::cin >> complex._Val[0] >> complex._Val[1];
std::cout << complex << std::endl;
}
Allows for the first form "1.2 6.2" for instance. For the second form, read in a string and parse it.
-
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:
Code:
complex<float> bob;
float x, y;
cin >> x >> y;
stringstream foo;
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::complex<float> complex_num;
std::cout << "Enter complex number: ";
std::cin >> complex_num;