0

I am writing some hobby code today for fun, and while I did some stuff I came along something interesting that I would like to do in a way that sounds and looks nice/great/cool.

The idea is basically that you have a string in C++ and you pass it to a stringstream (to construct the ss).

Then, the expected format is <int or string> <string>, and you would get the correct output according to the user input like:

bool ExecuteSendPrivateMessage(int sender, std::string params)
{
    std::stringstream sparams(params);
    int_or_string receiverid;
    std::string message;

    sparams >> receiverid >> message;

    if (sparams.fail())
    {
        std::cout << "usage: /send_message_to <userid/username> <message>" << std::endl;
        return true;
    }
    if (int_or_string.HasString())
    {
        receiverid = GetUseridFromUsername(int_or_string.GetString());
    }
    SendMessage(receiverid.GetInt(), message);
    return true;
}

Is this possible in C++? Or with C++ in combination with Boost?

Assuming no user has a name with only numerical characters?

Gizmo
  • 1,990
  • 1
  • 24
  • 50
  • What exactly do you mean with _'smart format'_ feature? – πάντα ῥεῖ Oct 25 '14 at 11:35
  • making `operator >>` distinguish from a set of possibilities and assigning the correct value to the correct variable? like in the example :) – Gizmo Oct 25 '14 at 11:36
  • You may be after something I've been pointing out in [this question](http://stackoverflow.com/questions/24504582/test-whether-stringstream-operator-has-parsed-a-bad-type?noredirect=1#comment37965807_24504582). – πάντα ῥεῖ Oct 25 '14 at 11:37
  • You can write grammars that include specific types of input in a specific order using Boost Spirit (Qi). Here is the employee parsing example: http://www.boost.org/doc/libs/1_48_0/libs/spirit/doc/html/spirit/qi/tutorials/employee___parsing_into_structs.html For the simple case in your example it's probably overkill. – jogojapan Oct 25 '14 at 11:40

1 Answers1

2

Is kind of a hacky way, but what I would do is put receiverid into a stringstream and then try to read into an int from the stringstream. If the sstream's fail flag is set than we must have a string, so we use the initial receiver id.

Something like this:

std::string recieverid;
std::stringstream srecieverid(recieverid);
int irecieverid;
srecieverid >> irecieverid;
if(srecieverid.fail()) {
   irecieverid = GetUseridFromUsername(recieverid);
}
SendMessage(irecieverid, message);

It isn't really the cleanest way, but it works.

Alex
  • 467
  • 4
  • 13