4
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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
John
  • 541
  • 4
  • 13

2 Answers2

2

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;
}
Fred Nurk
  • 13,952
  • 4
  • 37
  • 63
  • 1
    Oh you could just do `copyfmt`... I guess you learn something new every day :) +1 ...(daily vote limit, grr.) – Skurmedel Feb 03 '11 at 17:33
  • Not sure I understand why we are doing the copyfmt, but I'll study it some more. Thanks! I assume I pass my oss variable into your float_w/o.. function and then keep using it as normal after that. – John Feb 04 '11 at 21:58
  • 1
    @user506225: Copying the format copies precision and any other relevant flags, however the width has to be excluded (reset to zero here) so you get the expected result. And yes, pass in your stream so this can write the final string to it, then continue using your stream normally. – Fred Nurk Feb 04 '11 at 23:15
1

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;
}
Skurmedel
  • 21,515
  • 5
  • 53
  • 66