%s not producing string representation of enum?

Basile B. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 10 06:46:26 PST 2015


On Thursday, 10 December 2015 at 14:24:43 UTC, Shriramana Sharma 
wrote:
> Hello. I'm using DMD 2.069.2. As per 
> http://ddili.org/ders/d.en/enum.html the following code is 
> supposed to output the *names* of the suits:
>
> import std.stdio;
> void main()
> {
>     enum Suit { spades, hearts, diamonds, clubs }
>     foreach (suit; Suit.min .. Suit.max + 1) { writefln("%s", 
> suit); }
> }
>
> But I'm getting 0 1 2 3. Kindly advise.

You should rather use std.traits.EnumMembers to iterate the 
members of an enum:

~~~~~~~~~~~~
import std.stdio;

void main(string[] args)
{
     import std.traits: EnumMembers;
     enum Suit { spades, hearts, diamonds, clubs }
     foreach(member; EnumMembers!Suit)
         writeln(member);
}
~~~~~~~~~~~~

it can also counts

~~~~~~~~~~~~
import std.stdio;

void main(string[] args)
{
     import std.traits: EnumMembers;
     enum Suit { spades = 23.2, hearts, diamonds, clubs }
     foreach(i,member; EnumMembers!Suit)
     {
         writeln(member);
         writeln(i);
     }
}
~~~~~~~~~~~~

which is interesting to get the rank of a member, considering 
that the rank is not always the same as the value (like here, 
it's a float ;) ).


More information about the Digitalmars-d-learn mailing list