2010-05-15 137 views
50

我想輸出一個整數爲std::stringstream等效格式爲printf%02d。是否有更簡單的方法來實現這一目標比:等同於%02d與std :: stringstream?

std::stringstream stream; 
stream.setfill('0'); 
stream.setw(2); 
stream << value; 

是否有可能流某種格式標誌的stringstream,像(僞):

stream << flags("%02d") << value; 
+5

不應該是'stream.fill('0')'和'stream.width(2)'?你正在使用操縱器的名字,就像你知道自己問題的答案一樣? – 2010-05-15 09:34:31

回答

63

您可以使用<iomanip>中的標準機械手,但是沒有一個整齊的fillwidth一次:

stream << std::setfill('0') << std::setw(2) << value; 

它不會是很難寫自己的對象,當插入到流中執行兩個功能:

stream << myfillandw('0', 2) << value; 

例如

struct myfillandw 
{ 
    myfillandw(char f, int w) 
     : fill(f), width(w) {} 

    char fill; 
    int width; 
}; 

std::ostream& operator<<(std::ostream& o, const myfillandw& a) 
{ 
    o.fill(a.fill); 
    o.width(a.width); 
    return o; 
} 
9

您可以使用

stream<<setfill('0')<<setw(2)<<value; 
9

你不能在標準C++中做得更好。另外,您也可以使用Boost.Format庫:

stream << boost::format("%|02|")%value; 
+1

如果你沒有使用'stream'作爲其他任何東西,你不需要它,因爲'boost :: format'已經產生了一個字符串。 – UncleBens 2010-05-15 09:51:40

+1

我聽說你必須把它傳遞給'str(...)'然後 – 2010-05-15 10:18:41

+0

Jahonnes你可以使用std :: string myStr =(boost :: format(「%| 02 |」)%value).str(); – 2013-03-06 09:01:27

0

是否有可能流某種格式標誌的stringstream

不幸的是,標準庫不支持將格式說明爲字符串,但您可以用fmt library做到這一點:

std::string result = fmt::format("{:02}", value); // Python syntax 

std::string result = fmt::sprintf("%02d", value); // printf syntax 

,你甚至不需要構建std::stringstreamformat函數將直接返回一個字符串。

免責聲明:我是fmt library的作者。