Recommended Posts

Hi, I'm just wondering how a function like printf uses the ... part? I've got this function: void LogFile::WriteLine(const char *text,...) { m_pFile = fopen(m_Filename,"a"); // fprintf(m_pFile,text,...); fclose(m_pFile); } ...you get the intention of the commented line.. but how do you do it properly? Thanks.

Share this post


Link to post
Share on other sites
Check out your compiler's documentation for the header file "stdarg.h". That file holds the functions and macros which can use vararg lists. Note, however, that in C++ it is an exceedingly bad idea to use varargs, because they throw away type safety and have problems with cleaning up after themselves. Beware, beware, beware.

Share this post


Link to post
Share on other sites
likeregularchickens,

Check out va_start, va_begin, va_end under <stdargs.h> You can use these calls to merge those kind of strings together.

-brad

Share this post


Link to post
Share on other sites
Sneftel's got it covered, I'll expand on the alternatives:

1) Chaining.

void LogFile::WriteLine( const char * format , ... )

You could do:

LogFile & LogFile::Write( int number ) {
...
return *this;
}

LogFile & LogFile::Write( const std::string & string ) {
...
return *this;
}

LogFile mylog;
mylog.Write( 13 ).Write( "Example string" );


To replace this clunky usage with a familliar one, we simply switch our function names from "Write" to "operator<<" and our example use to:

mylog << 13 << "Example string";


This is known as operator chaining, a powerful technique used by the standard library's iostreams.

2) Chaining... using someone else's library

The Boost C++ Libraries have an excelent utility called boost::format. Here's an example:

int foo = 13;
std::string bar = "pie";

cout << boost::format("%1% %2%") % foo % bar << endl; //result: 13 pie
std::string result = str( boost::format("%1% %2%") % foo % bar ); //result: result == "13 pie"

LogFile & LogFile::Write( const std::string & string ) {
...
}

mylog.Write( str( boost::format( "%1% %2%" ) % foo % bar ) );


Thank you, thank you very much.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this