I have the following very simple class:
class accusation
{
private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream&, accusation&);
};
I have overloaded my extraction from istream operator as follows:
std::istream& operator>>(std::istream& is, accusation& readable)
{
std::vector<std::string> accusation;
std::string token, word;
//divide by commas
while (std::getline(is, token, ','))
{
std::string pushable;
std::stringstream ss(token);
while (ss >> word) pushable += word + " ";
if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
accusation.push_back(pushable);
}
if (accusation.size() == 3)
{
is.clear();
bool valid{ false };
//check it matches one of the clue::characters
for (const auto& character : clue::characters)
if (accusation[0] == character)
{
valid = true;
break;
}
if (valid)
{
valid = false;
//check it matches one of the clue::weapons
for (const auto& weapon : clue::weapons)
if (accusation[1] == weapon)
{
valid = true;
break;
}
if (valid)
{
valid = false;
//check it matches one of the clue::places
for (const auto& place : clue::places)
if (accusation[2] == place)
{
valid = true;
break;
}
if (valid)
{
readable.murderer = accusation[0];
readable.weapon = accusation[1];
readable.place = accusation[2];
}
else
is.setstate(std::ios_base::failbit);
}
else
is.setstate(std::ios_base::failbit);
}
else
is.setstate(std::ios_base::failbit);
}
else
is.setstate(std::ios_base::failbit);
return is;
}
I am reading input as green, dagger, kitchen
and storing it in my accusation. The first element has to be in clue::characters
(an array of possible game characters), second element in clue::weapons
, and third element in clue::places
.
Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is a lot of space for improvements. Any push into the right direction is highly appreciated.