std::ostringstream oss;
oss << std::setw(10);
oss << std::setfill(' ');
oss << std::setprecision(3);
float value = .1;
oss << value

I can check if value < 1 and then find the leading zero and remove it. Not very elegant.

有帮助吗?

解决方案

I can check if value < 1 and then find the leading zero and remove it. Not very elegant.

Agreed, but that's what you have to do without mucking around in locales to define your own version of ostream::operator<<(float). (You do not want to do this mucking around.)

void float_without_leading_zero(float x, std::ostream &out) {
  std::ostringstream ss;
  ss.copyfmt(out);
  ss.width(0);
  ss << x;
  std::string s = ss.str();
  if (s.size() > 1 && s[0] == '0') {
    s.erase(0);
  }
  out << s;
}

其他提示

You could write your own manipulator. The elegance is of course debatable. It would more or less be what you've all ready proposed though.

Example:

struct myfloat
{
    myfloat(float n) : _n(n) {}

    float n() const { return _n; }

private:
    float _n;
};

std::ostream &<<(std::ostream &out, myfloat mf)
{
    if (mf.n() < 0f)
    {
        // Efficiency of this is solution is questionable :)
        std::ios_base::fmtflags flags = out.flags();
        std::ostringstream convert;
        convert.flags(flags);
        convert << mf.n();

        std::string result;
        convert >> result;

        if (result.length() > 1)
            return out << result.substr(1);
        else
            return out << result;
    }
    return out;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top