void do_test( Character *ch, char *argument )
{
std::ostringstream buf;
buf << "Hi, my name is " << ch->name << << "\r\n";
buf << "I am level: " << ch->level << << "\r\n";
buf << "The first item in my inventory is " <<
(ch->carrying ? ch->carrying->short_desc : "(nothing)") << "\r\n";
ch->stream(buf);
}
// in character.cpp
void Character::stream(std::ostringstream &stm)
{
send(stm.str().c_str());
}
ch << "This is a silly message\r\n";
#include <string>
#include <iostream>
#include <cstdarg>
#include <cstdio>
using namespace std;
void string_printf(string const &str, …)
{
va_list args;
char buf[1024];
char const *fmt = str.c_str();
va_start(args, str);
vsprintf(buf, fmt, args);
va_end(args);
cout << buf << endl;
}
int main()
{
string blah = "blah %s foo %d bar %s";
string_printf(blah, "ONE", 2, "THREE");
}
// can send formatted or unformatted strings to character.
void Character::send(const char *fmt, …)
{
// cast const to non const to accommodate const and non const arguments.
char *fmt2 = (char*) fmt;
char buf [MAX_STRING_LENGTH];
va_list args;
va_start (args, fmt2);
vsprintf (buf, fmt2, args);
va_end (args);
Server::instance()->sendCharacter(buf, this);
}
void Character::send(std::ostringstream &stm)
{
send(stm.str().c_str());
}
void Character::send(std::string &str)
{
send(str.c_str());
}
This doesn't work:
You cant send a const (fmt) into vsprintf().
I was hoping there would be a c++ algorithm that does something similar to C's <stdarg.h>
This is just kind of a wrapper for const char* fmt right now.
If there's a quick fix you might know of, I'll gladly take it, and put this off until I'm more comfortable with std strings.
EDIT:
I'm sure the question you might have is: "Why not just use char*?"
Well, the answer is: I guess I don't really have one. I just figured it might be a good idea. I think that it will make
customization like do_score() a breeze.