在 C++ 程序中,我有一些代码可以打印一个名为 fraction 的类的对象。它的变量是 n(分子)、d(分母)和 sinal(信号:当分数为正时为真,否则为假)。
ostream &operator << (ostream &os, const fraction &x){//n=0
if(!x.sinal)
os << "-";
os << x.n;
if(x.d!=1 && x.n!=0)
os << "/" << x.d;
return os;
}
它做得很好,但是当我尝试在其中使用 setw() 时,它无法正常工作:它只影响要打印的第一个项目(无论是信号还是分子)。
我尝试更改它,我找到的解决方案是首先将其转换为字符串,然后使用带有 iomanip 的操作系统:
ostream &operator << (ostream &os, const fraction &x){//n=0
string xd, xn;
stringstream ssn;
ssn << x.n;
ssn >> xn;
stringstream ssd;
ssd << x.d;
ssd >> xd;
string sfra = "";
if(!x.sinal)
sfra += "-";
sfra += xn;
if(x.d !=1 && x.n != 0){
sfra += "/";
sfra += xd;
}
os << setw (7) << left << sfra;
return os;
}
这行得通,但显然我无法更改分数的宽度:所有分数的宽度均为 7。有没有办法改变它?我真的需要为不同的分数使用不同的宽度。提前致谢。
最佳答案
那是因为,根据 https://stackoverflow.com/a/1533752 , 输出的 width
为每个格式化输出显式重置。
你可以做的是在你的函数开始时获取当前宽度,这是由 std::setw
(或相关的)设置的宽度,然后为每个值显式设置这个宽度在你想要应用它的地方,并为你想要按原样输出的每个值使用 std::setw(0)
:
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 << x.n;
if(x.d!=1 && x.n!=0)
os << "/" << std::setw(width) << x.d;
return os;
}
现在您需要对此进行一些改进以处理左右填充;这只处理左填充。
关于c++ - 带有类对象的 iomanip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30275084/