-
Notifications
You must be signed in to change notification settings - Fork 0
/
Complex.cpp
99 lines (81 loc) · 2.34 KB
/
Complex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <exception>
#include <iostream>
#include <sstream>
#define V_MINUS_TWO -2
#define V_ONE 1
#define V_PLUS_SIGN 0x2b
#define V_ZERO 0
//Class to handle custom exceptions.
class ComplexNumberFormatErrorException : public std::exception
{
public:
const char* what() const noexcept override
{
return "Damn! Invalid complex number format.";
}
};
//Definition of the 'Complex' class.
class Complex
{
public:
double dbl_real = V_ZERO;
double dbl_imaginary = V_ZERO;
//Default constructor.
Complex() : dbl_real(V_ZERO), dbl_imaginary(V_ZERO) {}
//Constructor with parameters.
Complex(double dbl_real, double dbl_imaginary) : dbl_real(dbl_real), dbl_imaginary(dbl_imaginary) {}
//Overloading of the '>>' operator.
friend std::istream& operator>>(std::istream& console_input, Complex& complex);
};
//Defining the '>>' operator overload for std::cin.
std::istream& operator>> (std::istream& input, Complex& complex)
{
std::string inputStr;
input >> inputStr;
//Find the position of the '+' symbol.
size_t plusPos = inputStr.find(V_PLUS_SIGN);
if (plusPos == std::string::npos)
{
//Handle error if format is not correct.
input.setstate(std::ios::failbit);
throw ComplexNumberFormatErrorException();
}
else
{
//Extract the real part and the imaginary part of the complex number from the character string as decimals.
try
{
complex.dbl_real = std::stod(inputStr.substr(V_ZERO, plusPos));
complex.dbl_imaginary = std::stod(inputStr.substr(plusPos + V_ONE, inputStr.length() - plusPos + V_MINUS_TWO)); //-2 to remove 'i'.
}
catch (std::exception& ex)
{
std::cerr << '\x5b' << ex.what() << '\x5d' << std::endl;
}
}
return input;
}
int main()
{
Complex c;
std::cout << "Enter a complex number of the form: 'a+bi': ";
//Testing and obtaining the complex number of the form: 'a+bi'.
try
{
std::cin >> c;
}
catch (std::exception& ex)
{
std::cerr << '\x5b' << ex.what() << '\x5d' << std::endl;
}
//Sets flag on input as invalid complex number format.
if (std::cin.fail())
{
std::cerr << "Mistake! Incorrect input complex number format." << std::endl;
}
else
{
std::cout << "Complex number entered: [" << c.dbl_real << "] + [" << c.dbl_imaginary << "]i." << std::endl;
}
return V_ZERO;
}