简体   繁体   中英

C++ Random number to print string in an array

I am working on a school project where I need to create a fortune cookie program. The basics of the program is that it create a random number which is then assigned to a "fortune" in an array that will print out on the screen. I need help on getting the random number that is generated to print out the pre-defined string in an array.

Also to make it look fancy I'd like to make a for loop that will create a border around each fortune, since they are different lengths, so it looks cohesive and will look better than having to do it manually.

Any assistance will be helpful

Here's the code:

fortunecookie.h

#ifndef FORTUNECOOKIE_H_INCLUDED
#define FORTUNECOOKIE_H_INCLUDED
#include <cstring>
#include <cstdlib>

using namespace std;

class Fortunecookie
{
private:
   string fortune[10];
   int rand_index;
public:
   void openFortuneCookie();
   void generateNewFortune();
   FortuneCookie();
};

#endif // FORTUNECOOKIE_H_INCLUDED

fortunecookie.cpp

#include <iostream>
#include <ctime>
#include "fortunecookie.h"
using namespace std;


void Fortunecookie::generateNewFortune()
{
string fortune [10] = {" One that would have the fruit must climb the tree",
                   " A new opportunity awaits you at the fork of the road",
                   " The early bird gets the worm, but the second mouse gets     the cheese. ",
                   " You are cleverly disguised as responsible adult.",
                   " The best things in life aren't things",
                   " Forget injuries; never forget kindnesses.",
                   " Borrow money from a pessimist. They don't expect it       back",
                   " Your good enough, strong enough and gosh darnit' people     like you",
                   " A feather in the hand is better than a bird in the     air. ",
                   " In life, you must be the water"
                  };
for (int i=0; i<10; i++)
{
   srand(time(0));
   rand_index = rand() %10 +1;
}
}

Fortunecookie::FortuneCookie()
{
if (rand_index == 1)
{
    fortune[1]=rand_index;
}
if (rand_index == 2)
{
    fortune[2]=rand_index;
}
if (rand_index == 3)
{
    fortune[3]=rand_index;
}
if (rand_index == 4)
{
    fortune[4]=rand_index;
}
if (rand_index == 5)
{
    fortune[5]=rand_index;
}
if (rand_index == 6)
{
    fortune[6]=rand_index;
}
if (rand_index == 7)
{
    fortune[7]=rand_index;
}
if (rand_index == 8)
{
    fortune[8]=rand_index;
}
if (rand_index == 9)
{
    fortune[9]=rand_index;
}
if (rand_index == 10)
{
    fortune[10]=rand_index;
}
}
void Fortunecookie::openFortuneCookie()
{

Fortunecookie::generateNewFortune();

cout << " |====================================================================| \n";
cout << " |\t\t\t\t\t\t\t\t      | \n";
cout << " |\t\t\t\t\t" <<rand_index<< "\t\t\t      |\n";
cout << " |\t\t\t\t\t\t\t\t      | \n";
cout << "     |====================================================================| \n";

}

main.cpp

#include <iostream>
#include "fortunecookie.h"
 using namespace std;

 int main ()
 {
 Fortunecookie yourfortune;
 yourfortune.generateNewFortune();
 yourfortune.FortuneCookie();
 yourfortune.openFortuneCookie();
 return 0;
 }

Here are the project details:

For this lab you will create a Fortune Cookie class. Upload compressed file containing the three files for this program.

  - fortunecookie.h
  - fortunecookie.cpp
  - fortuneDriver.cpp

Each fortune cookie will have an array of 10 strings that will hold different fortunes. You can make up the 10 fortunes. One of those fortunes will be the active one. That active fortune will be selected by generating a random number for an index in the array.

The fortune cookie will have the following methods:

void generateNewFortune(); Summary: This function creates a new random index that represents a different fortune. The fortunes are stored in a string array called fortunes, of size 10. Preconditions: The array of 10 fortunes has been initialized so that there are no empty strings. Postconditions: A new index between 0 - 9 has been generated and assigned to rand_index.

void openFortuneCookie(); Summary: This function displays the fortune at rand_index in the array // of strings. Sample output shown below:

|=========================| | You will get great news!| |=========================|

Preconditions: The string array with fortunes has been initialized. The rand_index has been assigned a value from 0 to 9. Postconditions: A random fortune is displayed with the format shown above.

FortuneCookie(); Summary: The default constructor assigns a fortune to each index in the fortunes array. It also initializes the rand_index to a random number from 0 to 9. Preconditions: FortuneCookie has garbage values in the variables. Postconditions: The FortuneCookie object has been initialized so that rand_index has a value from 0 – 9 and the array of fortunes has a fortune at each index.

There are a couple of errors in this code:

  • First C++ is case-sensitive, so you have to chose once for good it it's Fortunecookie or FortuneCookie .
  • The default constructor is the first thing that is created when you construct a new cookie. According to the requirements, there you should initialize the fortune strings.
  • in main() you should not call the default constructor explicitly. It is called in the statement were you define the object.
  • You try to initialize fortunes you write in a member function string fortune [10] = {...}; . Unfortunatley this is a declaration of a local fortune array that hides the fortune array of the class and which you hoped to initialize
  • the index shall be between 0 and 9, or you'll go out of range.
  • The sequence where you try to set the fortune in a long if chain is puzzling.

Adjusted main() :

int main ()
{
    srand(time(0));                    // only once, at the beginning of the programme
    Fortunecookie yourfortune;         // this calls the default constructor
    //yourfortune.generateNewFortune();// not needed, you call it in openFortune()
    //yourfortune.Fortunecookie();       // OUCH !!
    yourfortune.openFortuneCookie();
    return 0;
}

The constructor should then take over the string initialization. Here an example with a fixed string array as initializer. But you could also assigne each array element individually:

Fortunecookie::Fortunecookie()
               : fortune{" One that would have the fruit must climb the tree",
                   " A new opportunity awaits you at the fork of the road",
                   " The early bird gets the worm, but the second mouse gets     the cheese. ",
                   " You are cleverly disguised as responsible adult.",
                   " The best things in life aren't things",
                   " Forget injuries; never forget kindnesses.",
                   " Borrow money from a pessimist. They don't expect it       back",
                   " Your good enough, strong enough and gosh darnit' people     like you",
                   " A feather in the hand is better than a bird in the     air. ",
                   " In life, you must be the water"
                  }
{
    rand_index = rand() %10;  // number between 0 and 9 
}

The generation of a new cookie is then simplified (although you could get rid of this function completely, since the index is already initialized with a random number in the cookie creation):

void Fortunecookie::generateNewFortune()
{
    rand_index = rand() %10;
}

You could also improve the printing of the fortune by adding the string:

void Fortunecookie::openFortuneCookie()
{
    generateNewFortune();

    cout << " |====================================================================| \n";
    cout << " |                                                                    | \n";
    cout << " | " <<setw(2)<<rand_index+1<<"-"<<setw(63)<<fortune[rand_index]<< " |\n";
    cout << " |                                                                    | \n";
    cout << " |====================================================================| \n";
}

Infally, here an online demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM