In c++, what can we do to format the output just as we want?

Hi,
For example, if my output is: -

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


Then, what can I do to show it like: -

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


Can anyone help?
Last edited on
Last edited on
@mutexe: Is that the only way?
Last edited on
if you want the 'of' each line in the same place you may have to do more than that actually (I think).
@mutexe: Yes, you nailed it! I want the 'of''s in the same place. What do you think I need to do more? And can setw help?
Last edited on
You can use the iomanip header file and then use the left and right manipulators on the face and suit string variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <random>
#include <algorithm>

struct Card
{
    enum Suit { Spades, Hearts, Clubs, Diamonds };
    enum Face { Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };

    static const unsigned longestFace = 5;

    Suit suit;
    Face face;
};

std::string as_string(Card::Suit suit)
{
    static const char* suit_str[] = { "Spades", "Hearts", "Clubs", "Diamonds" };
    return suit_str[suit];
}

std::string as_string(Card::Face face)
{
    static const char* face_str[] = { 
        "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven",
        "Eight", "Nine", "Ten", "Jack", "Queen", "King" 
    };

    return face_str[face];
}

std::ostream& operator<<(std::ostream& os, Card c)
{
    os << std::right << std::setw(Card::longestFace);
    os << as_string(c.face) << " of " << as_string(c.suit) ;

    return os;
}

template <typename iter_type>
void printCards(iter_type beg, iter_type end)
{
    while (beg != end)
        std::cout << *beg++ << '\n';
}

int main()
{
    std::vector<Card> cards;
    for ( unsigned s=0; s<4; ++s)
        for (unsigned f = 0; f < 13; ++f)
            cards.push_back({ Card::Suit(s), Card::Face(f) });

    std::mt19937 rng((std::random_device())());

    for (unsigned runs = 0; runs < 5; ++runs)
    {
        std::shuffle(cards.begin(), cards.end(), rng);
        printCards(cards.begin(), cards.begin() + 5);
        std::cout << '\n';
    }
}


http://ideone.com/svOMtQ
Hey cire, thanks a lot. It really helped me.
Topic archived. No new replies allowed.