So I've already got one function that takes a list of va_args, ..., and then formats it, like such

string form_string(string format, ...)
{
	va_list args;
	va_start(args, format);
	ostringstream output("");

	for (unsigned int i = 0; i < format.length(); i++) {
		if (format[i] == '%' && format[i+1] != '%' && i+1 < format.length()) {
			switch (format[i+1]) {
				case 's':
					char *temp = va_arg (*args, char*);
					output << temp;
					break;
				case 'd':
					int Temp = va_arg (*args, int);
					output << Temp;
					break;
				default:
					output << format[i];
			}
			i++;
		}
		else {
			output << format[i];
		}
	}
	va_end(args);

	return output.str();
}

which works fine, because I'm actually using it to log messages to a file, rather than just print out and I didn't want to be restricted by vsprintf and the like.

Anyway, what I'd love to do is have a few different variations, which act slightly differently, one which prints the date and time at the start of the line

char tmp[100] = "";
	time_t t = time(NULL);
	strftime(tmp, 99, "[%Y/%m/%d %H:%M:%S]: ", localtime(&t));

One which logs it to a file, as I stated above and one which returns it as a const char*, rather than a string.

My question is is there any way to efficiently pass the ... section to one overall function, which formats it and then the individual functions do their special function?

I've currently got an effort working like

string with_time(string format, ...) {
	va_list args;
	va_start(args, format);

	char tmp[100] = "";
	time_t t = time(NULL);
	strftime(tmp, 99, "[%Y/%m/%d %H:%M:%S]: ", localtime(&t));

	return formatit((string)tmp+format, &args);
}

string formatit(string format, va_list* args) {
	... works as above, but without va_start and *args in place of args ...
}

but in this way, I have to repeat the two lines

va_list args;
	va_start(args, format);

for every specific function I want something different to happen.

I don't want to add in any other arguments to any of the functions, only the format of the string and the ... arguments. As far as I can see, I can't see any other way to pass the ... arguments, other than through the "va_list args" and va_start lines, am I wrong in thinking that, or is there another, more efficient way which I can do this?

>I can't see any other way to pass the ... arguments, other than
>through the "va_list args" and va_start lines, am I wrong in thinking that
Nope, you're right on track.

While I'm slightly disappointed that there isn't another way, I'm a bit proud... this is the first post where I've posted for help and the first reply is telling me I'm doing things properly, :)

It's a good day today!

This article has been dead for over six months. Start a new discussion instead.