I have a problem. I try to print properly by using setprecision, but still, my result is wrong. This is my input data.txt
(1.1,2) (1.7,3.14)
This is my output result.txt
1.1, 2,
0.7, 3.1,
This is output, which I expect
1.10, 2.00
1.70, 3.14
This is my code
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
class Complex_num {
double real, imag;
public:
Complex_num(double r=0,double i=0){
real=r;
imag=i;
}
friend std::ostream& operator<<(std::ostream& os, const Complex_num& c)
{
return os << c.real << ", " << c.imag << setprecision(2) << ',' << ' '<<endl;
}
friend std::istream& operator>>(std::istream& is, Complex_num& cn){
char c;
return is>>c>>cn.real>>c>>cn.imag>>c>>c;
}
};
int main(int argc, char* argv[])
{
char c;
ifstream read(argv[1]);
if (!read)
{ cerr << "Open error: " << argv[1] << endl; exit(1);}
ofstream write(argv[2]);
if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
read.clear();
read.seekg(0);
Complex_num x1;
read >> x1;
write << x1;
cout << x1;
Complex_num x2;
read >> x2;
write << x2;
cout << x2;
return 0;
}
Why this is not working, I use set precision, but instead of 2.00, I get 2, and instead of 3.14 I get 3.1. Why?
setprecision
by default affects the number of significant digits printed, not the number of decimal places printed. To make it do that you have to switch to fixed output mode. Also you need to set the precision before you output the numbers not afterwards.
return os << fixed << setprecision(2) << c.real << ", " << c.imag << ',' << ' '<<endl;