2011-02-03 40 views
4
std::ostringstream oss; 
oss << std::setw(10); 
oss << std::setfill(' '); 
oss << std::setprecision(3); 
float value = .1; 
oss << value 

我可以檢查值是否爲< 1然後找到前導零並將其刪除。不是很優雅。如何將float .1設置爲.1而不是0.1

回答

2

我可以檢查是否值< 1,然後找到前導零並將其刪除。不是很優雅。

同意,但這是你有沒有語言環境碴周圍定義自己的版本的ostream的::運算< <(浮動)做什麼。 (你不想這樣做。)

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; 
} 
+1

哦,你可能只是做`copyfmt` ...我想你每天學習:) +1一些新的東西... – Skurmedel 2011-02-03 17:33:47

1

你可以write your own manipulator。優雅當然是有爭議的。這或多或少是你已經準備好的建議。

例子:

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; 
} 
相關問題