The following example demonstrates the use of complex input and output operators:
// An example of complex input and output
#include <complex.h> // required for use of Complex Mathematics Library
#include <iostream.h> // required for use of I/O Stream input and output
int main(int argc, char *argv[]) {
complex a [3]={1.0,2.0,complex(3.0,-3.0)};
complex b [3];
complex c [3];
complex d;
// read input for all of arrays b and c
// (you must specify each element individually)
cout << “Enter three complex values separated by spaces:” << endl;
cin >> b[0] >> b[1] >> b[2];
cout << “Enter three more complex values:” << endl;
cin >> c[2] >> c[0] >> c[1];
// read input for scalar d
cout << “Enter one more complex value:” << endl;
cin >> d;
// Note that you cannot use the above notation for arrays.
// For example, cin >> a; is incorrect because a is a complex array.
// Display each array of three complex numbers, then the complex scalar
cout << “Here are some elements of arrays a,b,and c:\n”
<< a[2] << endl
<< b[0] << b[1] << b[2] << endl
<< c[1] << endl
<< “Here is scalar d: ”
<< d << endl
// cout << a produces an address, not a list of array elements:
<< “Here is the address of array a:” << endl
<< a
<< endl; //endl flushes the output stream
return 0;
}
This example produces the output shown below in regular type, given the input shown in bold. Notice that you can insert white space within a complex number, between the brackets, numbers, and comma. However, you cannot insert white space within the real or imaginary part of the number. The address displayed may be different, or in a different format, than the address shown, depending on the operating system, hardware, and other factors:
Enter three complex values separated by spaces: 38 (12.2,3.14159) (1712,-33) Enter three more complex values: ( 17.1234 , 1234.17) ( 27, 12) (-33 ,0) Enter one more complex value: 17 Here are some elements of arrays a,b,and c: ( 3, -3) ( 38, 0)( 12.2, 3.14159)( 1712, -33) ( -33, 0) Here is scalar d:( 17, 0) Here is the address of array a: 0x2ff21cc0
Related Concepts
Related Tasks