Codet Codet - 2 months ago 27
C++ Question

C++ Randomly select from string array

I'm trying to devise a function that randomly selects three of the five strings and displays them on the screen. Here's what I have so far. It runs but nothing prints to the screen.

#include "BoxOfProduce.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>


using namespace std;

BoxOfProduce::BoxOfProduce()
:choices{""}, bundles{""}
{

}

vector<string> BoxOfProduce::randomize()
{
srand(time(0));
string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};

vector<string> random;
for(int i = 0; i < 3; i++)
{
random.push_back(choices[rand() % 5]);
}
return random;
}


#ifndef BOXOFPRODUCE_H
#define BOXOFPRODUCE_H
#include <iostream>
#include <string>
#include <vector>
#include <memory>

using namespace std;


class BoxOfProduce
{
public:
BoxOfProduce();
string getBundles();
void setBundles(string b);
vector<string> randomize();

private:
string bundles[3];
const string choices[5];
string random;
};

#endif // BOXOFPRODUCE_H


#include <iostream>
#include "BoxOfProduce.h"
#include <string>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <memory>

using namespace std;

int main()
{
srand(time(0));

BoxOfProduce bo;
bo.randomize();

auto vector<string> randomResult = bo.randomize();
for (const auto& result : randomResult){
cout << result << endl;
}
}


I have updated my code now and still no print output. Although I am getting an error:
error: range-based 'for' loops are not allowed in C++98 mode

I have never worked with auto before. So any help on this would be appreciated.

Answer

Your code should not compile. g++ emits the following error:

return random;
error: could not convert ‘random’ from ‘long int (*)()throw ()’

The random variable is local to your for-body. You should give it a greater scope:

string random;
for(int i = 0; i < 3; i++)
{
    random = choices[rand() % 5];
}
return random;

To produce the 3 results, you need to return a vector of string like

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

std::vector<string> randomize()
{
    srand(time(0));
    string choices[] = {"Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo"};

    std::vector<string> random;
    for(int i = 0; i < 3; i++)
    {
        random.push_back(choices[rand() % 5]);
    }
    return random;
}

int main()
{
    srand(time(0));

    randomize();
    std::vector<string> randomResult = randomize();
    for (std::vector<string>::const_iterator iter = randomResult.begin(), iterEnd = randomResult.end();
           iter != iterEnd; ++iter)
      cout << *iter << endl;
    return 0;
}
Comments