Convert const int to char*

F

Feroz

Hello Everyone,

Thanks for your responses in advance.

I have the following macro defined by a tool in a header file.

#define VERSIONSTRING 07,12,0003,0000

I need to read this into a char* in my .cpp. How do I do that? I tried
sprintf and itoa, but couldn't get it to work.


Regards,
F.
 
M

mlimber

Feroz said:
Hello Everyone,

Thanks for your responses in advance.

I have the following macro defined by a tool in a header file.

#define VERSIONSTRING 07,12,0003,0000

I need to read this into a char* in my .cpp. How do I do that? I tried
sprintf and itoa, but couldn't get it to work.

Since that's not in quotes, you'll need to pass it to a function lest
it be interpreted as an attempt to use the comma operator. In any case,
it's a bad way to do things (especially naming it *STRING), but you
could do it like this:

#include <sstream>
#include <iomanip>
using namespace std;

string ConvertVersion(
unsigned int a,
unsigned int b,
unsigned int c,
unsigned int d )
{
ostringstream ss;
ss << setfill('0')
<< setw(2) << a
<< setw(2) << b
<< setw(4) << c
<< setw(4) << d;
return ss.str();
}

void Foo()
{
const string ver = ConvertVersion( VERSIONSTRING );

// If you *must* use char* instead of std::string
const char *const cstr = ver.c_str();
// ...
}

Cheers! --M
 
F

foobish

Since you are in a cpp file, why not use a std::string const instead of
a #define? Then you can use the c_str() to return a const char* if you
really need to.

However, the #define would work if you were to define it like this:
#define VERSIONSTRING "07,12,0003,0000"
 
R

red floyd

Since you are in a cpp file, why not use a std::string const instead of
a #define? Then you can use the c_str() to return a const char* if you
really need to.

However, the #define would work if you were to define it like this:
#define VERSIONSTRING "07,12,0003,0000"

Better would be

#define VERSION 07,12,0003,0000
#define STR1_(x) #x
#define STR_(x) STR1_(x)
#define VERSIONSTRING STR_(VERSION)

That way you get both the string and the param list, and they're kept in
sync.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top