Search code examples
c++arraysfor-loopenumerator

C++ using enumerations with for loops to fill a float Array


My exercise is:

Write a program that gets the user's choice of color strength and transparency. Use a single enumeration for the colors and transparency - RED, GREEN, BLUE, ALPHA. Use a for loop that utilizes the enumeration set to iterate from RED up to ALPHA inclusive. Inside the for loop get the user to enter a value for each enumerated constant(i.e. a value for red, a value for blue, etc.) the values should be between 0.0 and 1.0 and stored in an array.

#include <string>
#include <iostream>

enum Difficulty
{
    RED,
    GREEN,
    BLUE,
    ALPHA

};

int main(int argc, char* argv[])
{

    char cColours[10][14] = { "RED", "GREEN", "BLUE", "ALPHA" };

    float fArray[4];
    int icounter = 0;

    while (icounter != 5)
    {

        std::cout << "For colour " << cColours[icounter] << " please enter a number ranging from 0.0 - 1.0 " << std::endl;
        std::cout << "press 10 to exit " << std::endl;


        for (int i = RED; i = ALPHA; i++)
        std::cin >> fArray[i];
        ++icounter;

    }

    system("pause");
    return 0;
}

Solution

  • According to comments you want to get one color mix (r,g,b,a). You use nested arrays for nothing.

    So one possible code:

    #include <iostream>
    #include <string>
    #include <stdio.h>
    
    enum ColorChannels {RED = 0, GREEN, BLUE, ALPHA, ALL_CHANNELS};
    /*Every enumeration gives values to its elements. In default the first element is zero,
    I illustrated this here. So ALL_CHANNELS (or difficulty if you want is equal with four,
    which is the number of all channels - this will be useful in loop*/
    
    int main(int argc, char* argv[])
    {
         std::string names[ALL_CHANNELS];
         names[RED] = "RED"; //this is same to names[0]
         names[1] = "GREEN";
         names[BLUE] = "BLUE";
         names[3] = "ALPHA";
         /*I'm not sure if char sequences work. If work, use it. I prefer more the strings*/
         float colorArray[ALL_CHANNELS];
    
         for (int i = 0; i < ALL_CHANNELS; i++)
         {
              std::cout << "Enter " << names[i] << " value between 0.0 and 1.0: ";
              //For instance "Enter RED value between 0.0 and 1.0: "
    
              //and NOW your read one parameter. You made a nested loop for nothing
              std::cin >> colorArray[i];
              std::cout << "\n"; //for a new line
         }
         // all elements read
    
         system("pause");
         return 0;
    }
    

    Try to do some improvements for exercise, like writing colors back; writing out if it is more likely red, blue or green; reading more colors; etc.