mardi 27 octobre 2015

rand() somtimes outputs blank lines, and other times it works just fine

When this program runs it's supposed to display 3 different fruits/vegetables at random (repeats are OK) but sometimes one or more of the outputs are blank and I'm not sure how to correct this. It also counts and displays how many times you chose to run the program.

Sometimes the output looks like this: Broccoli Kiwi Kiwi

And other times the output looks like this: (blank line) Tomato (blank line)

How do I fix this? I'm sure the problem is somewhere within the for-loop with boxInt

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

const int BOX_SIZE = 3;

class BoxOfProduce
{
public:
    BoxOfProduce();
    void displayWord(int boxInt);
    void input();
    void output();
    string Box[BOX_SIZE];

private:
    string full_list[5];
    static int count;
};


int BoxOfProduce::count = 0;


BoxOfProduce::BoxOfProduce()
{
    full_list[0] = { "Broccoli" };
    full_list[1] = { "Tomato" };
    full_list[2] = { "Kiwi" };
    full_list[3] = { "Kale" };
    full_list[4] = { "Tomatillo" };
}


void BoxOfProduce::input(){}


void BoxOfProduce::output()
{
    srand(time(0));

    int i;
    cout << "your bundle: " << endl;
    for (i = 0; i < 3; i++) // loop to execute code 3 times
    {
        int boxInt = rand() % 5; //make random number
        Box[i] = full_list[boxInt]; //add it to the Box
        displayWord(boxInt); //display it
    }
}
void BoxOfProduce::displayWord(int boxInt)
{
    cout << Box[boxInt] << endl;
}

int main()
{
    char userInput;
    static int counter = 0; // static variable for keeping track of how many boxes the user has opened

    do
    {
        cout << "Open new box of random produce? (y/n): ";
        cin >> userInput;

        if (userInput == 'y')
        {
            counter++;
            BoxOfProduce box1;
            box1.input();
            box1.output();

            cout << "\nCurrent number of produces boxes: " << counter << endl << endl;
        }
        else
        {
            return 0;
        }
    } while (userInput = 'y');

    system("pause");
}




Aucun commentaire:

Enregistrer un commentaire