Skip to main content
gamedev.net
🔒 Locked

...

Started by likeregularchickens 3 replies 400+ views
Original Post
likeregularchickens
likeregularchickens
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.
Sneftel
Sneftel
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.
Galapaegos
Galapaegos
likeregularchickens,

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

-brad
-brad
MaulingMonkey
MaulingMonkey
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 piestd::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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.