Convert from std::strong to char*

Recommended Posts

My log class takes a char* but since I want to put in a little more than just text a stringstream was easier; std::stringstream asd; asd << "this went wrong " << "error"; Log::Write(asd); But there it complains about the third line, "cannot convert parameter 1 from 'std::stringstream' to 'char *'". How do I do that conversion? Or is there some better way to do it?

Share on other sites
Log::Write (asd.str ().c_str ());

I suppose...

I'd make the the Log class work with std::string instead of char *, though... Using char * is painful and, in most cases, should be avoided.

Oxyd

Share on other sites
I guessed that but then I get:

cannot convert parameter 1 from 'const char *' to 'char *'

 The log class is taken here from gamedev, the function that performs the writing looks like this:

/************************************************************This is a static function that actually writes a line in the log.It flushes the log after every entry so that in a crash, the log file will have the info it needs.Input: line to logOutputs: writes a line to the log file************************************************************/void Log::Write(char* input, ...){	va_list arg;	va_start(arg, input);	if(log_file)	{		vfprintf(log_file, input, arg);		fprintf(log_file,"\n");		//be sure to flush the file so that the info gets to disk		fflush(log_file);	}	va_end(arg);}

I tried to convert it so it takes a std::string instead but I dont know what all the function does so I didnt edit anything.

Share on other sites
Since Log takes a char* instead of a const char*, this means that the function can modify the contents of the string. Because of this, you can't directly use the string returned by c_str( ), which must not be modified.

What you can do is create a modifiable buffer into which you dump the string data, and pass that buffer to the function.

char* buffer = new char[asd.str( ).size( )+1];
strcpy( buffer, asd.str( ).c_str( ) );
Log::Write( buffer );
delete [] buffer;

Share on other sites
Well - you'll probably have to make Log::Write accept const char * (second option is some kind of hackery with const_cast). It shouldn't make any difference, as long as you don't modify the string inside Log::Write.

EDIT: Your function should work fine, if you change it to void Log::Write(const char* input, ...)

Oxyd

Share on other sites
I would recomend reading up on const correctness, the C++ FAQ lite has a section on it here.

In this case I doubt your Log::Write function actually modifies the string in which case you need to have your Log::Write function take a const char*, like Oxyd said. If you need a modifiable char* string from a std::string you need to make which ToohrVyk showed.

Create an account

Register a new account

• Partner Spotlight

• Forum Statistics

• Total Topics
627653
• Total Posts
2978433

• 10
• 12
• 22
• 13
• 33