2014-01-29 29 views
-1

例如,如果我的輸出是: -在C++中,我能做些什麼來格式化我的輸出?

King of Spades 
Queen of Hearts 
Four of Diamonds 
Nine of Clubs 
Three of Diamonds 
Deuce of Spades 
Ace of Hearts 

然後,我能做些什麼來表現出來,如: -

King of Spades 
Queen of Hearts 
Four of Diamonds 
Nine of Clubs 
Three of Diamonds 
Deuce of Spades 
    Ace of Hearts 

我只需要對準of's。有人告訴我setw可以提供幫助。

是這樣嗎?如果可以的話,那麼如何?

+1

也許你應該查看'setw'的文檔,然後給它一個思考你可以如何使用它來解決問題? –

回答

2

計算你想要顯示的第一個單詞的最大長度然後調用setw。

cout << setw(5) << "Four" << " of " << "Hearts" << endl; 
cout << setw(5) << "Queen" << " of " << "Diamonds" << endl; 

明顯地用你的變量替換硬編碼的字符串。

2

如果你知道(在這種情況下5)最大字段寬度,那麼你的確可以使用setw墊的第一個字到寬度:

#include <iostream> 
#include <iomanip> 

std::cout << std::setw(5) << card.value << " of " << card.suit << std::endl; 

other manipulators這可能是興趣愛好,如如setfill指定填充填充的字符,而leftright指定填充字段的哪一側。

相關問題