Iomanip with class object

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.

+6
source share
1 answer

What, since fooobar.com/questions/35208 / ... , the width for the output is explicitly reset for each formatted output.

What you can do is at the beginning of your function, get the current width, which is the width set by std::setw (or related), and then explicitly set that width for each value you want to apply, and use std::setw(0) for each value you want to print as is:

 ostream &operator << (ostream &os, const fraction &x) { std::streamsize width = os.width(); if(!x.sinal) os << std::setw(width) << "-"; else os << std::setw(width); // Not necessary, but for explicitness. os << xn; if(xd!=1 && xn!=0) os << "/" << std::setw(width) << xd; return os; } 

Now you need to improve this a bit to handle left and right padding; it only handles left padding.

+1
source

Source: https://habr.com/ru/post/987332/


All Articles