In a C ++ program, I have code to print an object of a class called a fraction. Its variables are n (numerator), d (denominator) and sinusoidal (signal: true when the proportion is positive and false otherwise).
ostream &operator << (ostream &os, const fraction &x){//n=0 if(!x.sinal) os << "-"; os << xn; if(xd!=1 && xn!=0) os << "/" << xd; return os; }
This is a good job, but when I try to use setw () in it, it doesn’t work correctly: it just affects the first element to be printed (whether it is a signal or a numerator).
I tried changing it, and the solution I found was to convert it to a string first, and then use os with iomanip:
ostream &operator << (ostream &os, const fraction &x){//n=0 string xd, xn; stringstream ssn; ssn << xn; ssn >> xn; stringstream ssd; ssd << xd; ssd >> xd; string sfra = ""; if(!x.sinal) sfra += "-"; sfra += xn; if(xd !=1 && xn != 0){ sfra += "/"; sfra += xd; } os << setw (7) << left << sfra; return os; }
This works, but obviously I cannot change the width the fraction will have: it will be equal to 7 for all of them. Is there any way to change this? I really need to use different widths for different fractions. Thanks in advance.
source share