1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
// Example program
#include <iostream>
#include <string>
///
/// Parses a command sent to see if it's a /msg command,
/// and if so, returns true and puts the username and message to be sent
/// into username_out and message_out, respectively.
///
bool parse_message_command(const std::string full_command, std::string& username_out, std::string& message_out)
{
const std::string msg_token = "/msg ";
if (full_command.substr(0, msg_token.size()) == msg_token)
{
// assumes username immediately starts at index[5]
size_t space_after_username_index = full_command.find(" ", msg_token.size());
if (space_after_username_index != std::string::npos)
{
username_out = full_command.substr(msg_token.size(), space_after_username_index - msg_token.size());
message_out = full_command.substr(space_after_username_index);
if (message_out.size() >= 1)
message_out.erase(0, 1); // pop initial space off, if any.
return (message_out != "") && (username_out != "");
}
else
{
return false;
}
}
return false;
}
int main()
{
// get the username and message from user input
std::string full_command;
std::cout << ">";
std::getline(std::cin, full_command);
// variables to store the username and message in
std::string username;
std::string message;
// get the username and message
if (parse_message_command(full_command, username, message))
{
// use the username and message
std::cout << "Sending message \"" << message << "\" to \"" << username << "\"..." << std::endl;
}
else
{
std::cout << "Unknown command or incorrect syntax" << std::endl;
}
}
|