lundi 25 juin 2018

Write a function that randomly picks a string from array in C++

I am in a C++ beginning programming class and we are currently studying classes and constructors. I have been stuck on an assignment where we must write a function to randomly pick a color from our color array. Below is what I have so far. I think I am close but I am getting a compiler error and not sure how to fix it.

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

class ColorClass {
    public:
        ColorClass(string colors) {
            setColors(colors);
        }
        void setColors(string x) {
            colors[7] = x;
        }
        const string getColors() {
            return colors[7];
        }
        string randomizeColor(string x) {
            srand (time(NULL)); //initialize the random seed
            string word = x[rand() % 7]; //**get a compiler error here**
            return word;
        }
    private:
        string colors[7];
};

int main() {
    ColorClass colorClassInstance("Red, Orange, Yellow, Green, Blue, Purple, Indigo");

    cout << colorClassInstance.getColors() << endl;
    cout << colorClassInstance.randomizeColor(colorClassInstance.getColors()) << endl;

    return 0;
}

The compiler error is something like

no viable conversion from std::__1::basic_string...std::_1::allocator

(too long to type out, but hoping someone understands this on first glance).




Aucun commentaire:

Enregistrer un commentaire