0

I want that the user is able to enter the RGB colors one after one, I tried to keep the code simple as possible. The code below works, causes no errors, but I dont understand why its not in the correct order R > G > B, the first entered value is in this case the blue color, which is not wanted.

cout << "Enter successively red-, green, blue-part: " << endl;
c.setColor(readColor(cin), readColor(cin), readColor(cin));

setColor is defined:

void RGB_Color::setColor(int red, int green, int blue) {
    this->red = red;
    this->green = green;
    this->blue = blue;

readColor function:

int readColor(istream &stream)
{
    int i;
    stream >> i;
    return i;
}
Matej
  • 147
  • 2
  • 12

1 Answers1

0

The order of evaluation of function arguments is unspecified, so those readColor calls could occur in any order. A simple fix is to make the order explicit:

int r,g,b;
std::cin >> r >> g >> b;
c.setColor(r,g,b);

Another possibility would be to overload operator>> for RGB_Color (making it a friend if the member data is private):

std::istream& operator>> (std::istream& is, RGB_Color& color) {
    is >> color.red >> color.green >> color.blue;
    return is;
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193