-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomplex_ostringstream.cc
82 lines (77 loc) · 2.46 KB
/
complex_ostringstream.cc
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
#include <cerrno>
#include <cmath>
#include <complex>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
bool get_coeffs(ifstream &ifile, double arr[]) {
char instring[32];
int ctr = 0;
ifile.getline(instring, 32, '\n');
string line(instring), fragment;
if (line.length() == 0 || line[0] == '#')
return false;
istringstream iss(line);
while ((getline(iss, fragment, ' ')) && (ctr < 3)) {
if (fragment.length() == 0)
continue;
arr[ctr++] = atof(fragment.c_str());
}
if (ctr != 3)
return false;
return true;
}
int main(int argc, char **argv) {
if (argc != 3) {
cerr << "Usage: " << argv[0] << " <input file> <output file>" << endl;
exit(EXIT_FAILURE);
}
ifstream ifile(argv[1]);
if (!ifile) {
cerr << "Cannot open input file: " << argv[1] << endl;
exit(EXIT_FAILURE);
}
ofstream ofile(argv[2]);
if (!ofile) {
cerr << "Cannot open output file: " << argv[2] << endl;
exit(EXIT_FAILURE);
}
double coeffs[3], realroot1, realroot2, sqrt_disc;
ostringstream outbuf;
while (get_coeffs(ifile, coeffs)) {
ofile << "coeffs: " << coeffs[0] << '\t' << coeffs[1] << '\t' << coeffs[2]
<< endl;
outbuf << "coeffs: " << coeffs[0] << '\t' << coeffs[1] << '\t' << coeffs[2]
<< endl;
double discriminant = (coeffs[1] * coeffs[1]) - (4 * coeffs[0] * coeffs[2]),
denom = 1 / (2 * coeffs[0]);
if ((discriminant > 0) && (sqrt_disc = sqrt(discriminant))) {
realroot1 = (sqrt_disc - coeffs[1]) * denom;
realroot2 = (-1 * sqrt_disc - coeffs[1]) * denom;
} else if (discriminant == 0) {
realroot1 = -1 * coeffs[1] / (2 * coeffs[0]);
realroot2 = realroot1;
} else {
sqrt_disc = sqrt(-1 * discriminant);
complex<double> comproot1(-coeffs[1] * denom, -sqrt_disc * denom);
complex<double> comproot2(-coeffs[1] * denom, sqrt_disc * denom);
ofile << "roots: " << comproot1 << '\t' << comproot2 << endl;
outbuf << "roots: " << '\t' << comproot1 << '\t' << comproot2 << endl
<< endl;
}
if (discriminant >= 0) {
ofile << "roots: " << realroot1 << '\t' << realroot2 << endl;
outbuf << "roots: " << '\t' << realroot1 << '\t' << realroot2 << endl
<< endl;
}
}
// man std::ostringstream:
//__string_type str () const
// Copying out the string buffer.
cout << outbuf.str() << endl;
ofile << endl;
exit(EXIT_SUCCESS);
}