编写一个函数,在C ++中从数组中随机选择一个字符串

时间:2018-06-25 17:08:43

标签: c++ random constructor

我在C ++入门编程课程中,并且我们目前正在研究类和构造函数。我被困在一项分配中,在该分配中,我们必须编写一个函数以从颜色数组中随机选择一种颜色。以下是到目前为止的内容。我想我已经接近了,但是我遇到了编译器错误,不确定如何解决。

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

class ColorClass {
    public:
        ColorClass() {
            setColors();
        }
        void setColors() {
            colors[7] = {"Red, Orange, Yellow, Green, Blue, Purple, Indigo"};
        }
        const std::string getColors() {
            return colors[7];
        }
        std::string randomizeColor() {
            cout << "the colors are: " << colors;
            string word = colors[rand() % 7];
            cout << "word is :" << word;
            return word;
        }
    private:
        std::string colors[7];
};

int main() {
    srand (time(NULL)); //initialize the random seed
    ColorClass colorClass;
    colorClass.setColors();
    cout << colorClass.getColors() << endl;
    cout << colorClass.randomizeColor() << endl;

    colorClass.requirement();

    return 0;
}

编译器错误类似

  

没有从std :: __ 1 :: basic_string ... std :: _ 1 :: allocator转换

(输入时间太长,但希望有人乍一看就明白了)。

3 个答案:

答案 0 :(得分:1)

x[rand() % 7]是char类型的,您正尝试使用它初始化一个字符串。

如果这确实是您要执行的操作,请使用此构造函数从单个字符构建字符串:

string(1, x[rand() % 7])

答案 1 :(得分:1)

您的代码可能如下:

class ColorClass
{
    public:
        const std::vector<std::string>& getColors()  const { return colors; }

        void print() const {
            std::cout << "the colors are:\n";
            for (const auto& color : colors) {
                std::cout << color << std::endl;   
            }

        }

        const std::string& randomizeColor() const {
            return colors[rand() % colors.size()];
        }
    private:
        std::vector<std::string> colors = {"Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Indigo"};
};

int main() {
    srand (time(NULL)); //initialize the random seed

    ColorClass colorClass;
    colorClass.print();
    std::cout << "random pick:\n";
    for (int i = 0; i != 5; ++i) {
        std::cout << colorClass.randomizeColor() << std::endl;
    }
}

Demo

理想情况下,srand / rand应该替换为<random>中的新设施。

答案 2 :(得分:0)

我也是新手,但我看到如果不能分割字符串%7

string word = x[rand() % 7];

尝试替换字符串

可能是我不对:P