I am working on how to extract the real and imaginary component of a complex number (example 67 - 23i). My professor gave us a clue and said used the extraction operator>>.
I look on the website and never was surprise to see that they have these many choices
istream& operator>> (bool& val );
istream& operator>> (short& val );
istream& operator>> (unsignedshort& val );
istream& operator>> (int& val );
istream& operator>> (unsignedint& val );
istream& operator>> (long& val );
istream& operator>> (unsignedlong& val );
istream& operator>> (float& val );
istream& operator>> (double& val );
istream& operator>> (longdouble& val );
istream& operator>> (void*& val );
istream& operator>> (streambuf* sb );
istream& operator>> (istream& ( *pf )(istream&));
istream& operator>> (ios& ( *pf )(ios&));
istream& operator>> (ios_base& ( *pf )(ios_base&));
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signedchar& ch );
istream& operator>> (istream& is, unsignedchar& ch );
//GLOBAL FUNCTION
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signedchar* str );
istream& operator>> (istream& is, unsignedchar* str );
My question is:
1. Can use one of these functions, enter the complex number and immediately get the REAL and IMAGINARY part or do I write a code to parse my complex number myself to find the REAL amd IMAGINARY part?
I'm not too exPerinced in this, but I beleive that your imaginary number would be treated as an int. then you would need to parse the array using the '-' sign as the divider. The best thing to use is std::ifstream.getline()
There are many more than what you've listed, and there are other ways to parse strings besides the various overloads of operator>>, but to follow your requirements, it could be something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <sstream>
#include <complex>
int main()
{
std::istringstream buf("67 - 23i");
char minus, i;
double re, im;
buf >> re >> minus >> im >> i;
if(!buf || minus != '-' || i != 'i')
std::cout << "Parse error\n";
else
std::cout << std::complex<double>(re, im) << '\n';
}