Hamza Hajeir
Hamza Hajeir

Reputation: 416

Stringifying with leading zeros

I'm looking for a way to have a fixed length Device name in C++ at compile-time, as string literal.

For example :

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define VERSION 6
#define DEVICE_NAME "MyDevice" STR(VERSION)

A fixed length with leading zeros to fit 4 digits is my desired output, Just like as "MyDevice0006", The actual output using previous code is "MyDevice6".

I've searched and found this answer :

#undef VER
#define VER ...your version number...

#undef SMARTVER_HELPER_
#undef RESVER
#if VER < 10
#define SMARTVER_HELPER_(x) 000 ## x
#elif VER < 100
#define SMARTVER_HELPER_(x) 00 ## x
#elif VER < 1000
#define SMARTVER_HELPER_(x) 0 ## x
#else
#define SMARTVER_HELPER_(x) x
#endif
#define RESVER(x) SMARTVER_HELPER_(x)

But Trying it gives me the error :

error: expected ‘;’ before numeric constant
#define SMARTVER_HELPER_(x) 00 ## x
                            ^

Is there an enhanced code to do this ?

Upvotes: 1

Views: 229

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

Very ugly but this should do the trick:

#include <stdio.h>

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define VERSION 6

#if (version < 10)
    #define DEVICE_NAME "MyDevice000" STR(VERSION)
#elif (version < 100)
    #define DEVICE_NAME "MyDevice00" STR(VERSION)
#elif (version < 1000)
    #define DEVICE_NAME "MyDevice0" STR(VERSION)
#else
    #define DEVICE_NAME "MyDevice" STR(VERSION)
#endif

int main(void)
{
    puts(DEVICE_NAME);
}

Upvotes: 4

Related Questions