Hi guys im trying to generate 5 random numbers that return a string so i can compare it to a file.
so far i have this but i have no idea how to make it a string. Since i have to compare it to the file i mentioned earlier. This is my assignment and what i have so far.
A lottery ticket buyer purchases 10 tickets a week. always playing the same 10 5-digit "lucky" combinations. Write a program that reads the numbers from an input file, initializes an array with these numbers and then lets the player enter this week's winning 5-digit numbers (Use random number generator to generate 5 numbers in the range 1 through 49 for the winning combinationrather than letting the user enter the winning number combination).

The program should perform both, linear and binary search though the list of the player's numbers and report whether or not one of the tickets is a winner this week. You should present the user with the menu to find out if he/she is a winner through linear or binary search.

Here are the numbers:

11-18-20-24-25
8-10-23-32-36
1-6-12-18-34
23-29-31-32-34
1-15-17-23-32
4-6-13-25-27
8-9-26-29-34
14-17-19-24-30
1-8-25-28-29
13-17-24-29-33

srand((unsigned)time(0));
for(int i=0; i < 5; i++)
{
random_integer = (rand()%49)+1;
cout << random_integer ;
}

Recommended Answers

All 25 Replies

Well if you have five numbers to store, might as well make an array and store them in the array.

int random_integer[5];

Now fill in the array.

Once you have that, you'll need some way of converting 5 numbers to a string.

string toString(int array[], const int array_size)
{
    // go through the array.  Convert each integer to a string and concatenate them.  Put a dash in between each string.
}

Now you need a way to convert an int to a string. You have three choices...

  1. Use the itoa function. Down-side is that itoa isn't standard and works on C-Strings rather that C++ strings, so you have some converting to do.
  2. Write your own version of itoa using the / and % operators.
  3. Use stringstreams.

My vote is use option 2 or 3. Lots of threads on that. Type "C++ convert int to string" in the search box.

Hi VernonDozier! how've you been. I'm sorry but i dont understand your answer =[. so lemme just make sure i got it, this is my complete code just so that you have an idea of what im doing.

// strcmp(s1, s2)
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
#include <string>

using namespace std;
//Global Variable
const int MAX_SIZE = 50;

// Function Prototypes
int displayNumbers(fstream&, char[]);
int binarySearch(char[], int, int);
int searchList(int[], int, int);
void displayMenu(int);
void generateNumbers(int);
void draw();

int main(int argc, char *argv[])
{
    fstream lottoFile;                              //To read the numbers from a file
    char input[MAX_SIZE];                           //To hold the numbers
    int lottoFoundBinary,
        lottoFoundLinear,
        random_lotto;
    
    displayNumbers(lottoFile, input);
    
    generateNumbers(random_lotto);
        
    lottoFoundBinary = binarySearch(input, MAX_SIZE, random_lotto); 
    
       
    system("PAUSE");
    return EXIT_SUCCESS;
}

int displayNumbers(fstream &file, char nums[])
{
 file.open("lottonums.txt",ios::in); 
    
 if(!file)
    {
       cout <<"File Open Error!\n";
       return 0;
    }
    
    cout <<"Lottery Winners!\n"
         <<"----------------\n";
    cout <<"This is your lucky combination:\n"
         <<"Reading from file...\n\n";
    
 file.getline(nums, MAX_SIZE);
    while(!file.eof())
    {
       cout << nums << endl;
       file.getline(nums, MAX_SIZE);
    }
    file.close();    
}

int binarySearch(char array[],int numElems,int value) //function heading
{
	int first = 0;				    // First element of list
	int last = numElems - 1;	    // last element of the list
	int middle;					    // variable containing the current 
	int position = -1;              // middle value of the list
	bool found = false;
	
	while (!found && first <= last)
	{
		middle = (last + first) / 2; 
		   
	if (array[middle] == value)
		{
           found = true;
           position = middle;
        }
                                     
	else if (array[middle] > value)
		last = middle - 1;		   // toss out the second remaining half of
								   // the array and search the first 
	else
		first = middle + 1;		   // toss out the first remaining half of
								   // the array and search the second
	}
	
	return position;			   // indicates that value is not in the array
}

int searchList( int List[], int value, int numElems)
{
	for (int count = 0;count <= numElems; count++)  
	{
		if (List[count] == value)
                                                                                // each array entry is checked to see if it contains
	                                                                            // the desired value.
		 return count; 
                                                                                // if the desired value is found, the array subscript
			                                                                    // count is returned to indicate the location in the array
	}
	return -1;	                                                                // if the value is not found, -1 is returned
}

void displayMenu(int)
{

}

void generateNumbers(int random_integer)                                        // Function that calls the random combination
{
cout <<"\nNow lets see if we got the lucky numbers!\n";
cout <<"-----------------------------------------\n";

srand((unsigned)time(0));     
    for(int index=0; index<5; index++)
    {
    random_integer = (rand()%49)+1;         
    cout << random_integer
     << ". "; 
    }
    cout << endl;
}

This isn't going to do you any good at all, I don't think.

void generateNumbers(int);

It needs to be this...

void generateNumbers(int array[])

or possibly this...

void generateNumbers(int array[], const int arraySize)

Key word is "numbers"(plural), not "number"(singular), and you need to be able to get the numbers back after you generate them, so that means passing an array, not passing a single integer. Don't bother printing them in the function. Printing them does you no good at all. You need to be able to store them. You can print them later. Seems to me you need to be able to convert a string into an array and you need to be able to convert an array into a string, which appeared to be your original concern and is covered in my last post.

You are reading in strings from a file and you are expected to be able to search them. All of these searching function take arrays as parameters and they expect arrays of NUMBERS, not characters. You have at least some of them taking character arrays. That isn't going to work. So...you need to be able to convert a string consisting of integers separated by dashes into an array of integers and you need to be able to do the reverse. I wouldn't worry about any searches or random generation or file reading till I had those functions written. To split the string into integers, you'll need to familiarize yourself with the string library, possibly the atoi function, possibly the cctype library and concatenating strings as well as splitting them, so you may want to put this particular assignment aside for the moment if you are not familiar with them.

Okay, thank for your help. This assignment is due on monday. So ill go over the string library and come back for more help. Thats exactly what i have to do, i know i have to do em with string and separate each one of the numbers with a "-" but i have no idea how to do that and its really frustrating.

I think you'll find that the string library has just about everything you need.

http://www.cplusplus.com/reference/string/string/

There are numerous ways of doing all this, but they all involve some sort of picking apart strings. Your main two tools are "find" and "substr". You take a big string.

42-12-4-14-2

and you split it where the dashes are. So you set up a loop and "find" the index of the first dash using "find" or one of its cousins(anything with the word "find" in it).

You find the first dash at index 2 and you split the string into "42" and "12-4-14-2" using "substr". You've now isolated "42". Convert it to an integer as discussed and stick it in your array. Now work on "12-4-14-2" and do the same. Eventually there will be no more dashes and you're done.

That's one way. There are other ways, but only need one way. Pick one way and stick with it.

Okay, so how would i implement the string library to my program?? And lemme ask you something else, how do i compare them to my file and determine if i have a winner or not?? Once again, i really appreciate your help

>>how would i implement the string library to my program??

Stick

#include <string>

at the top.


>> how do i compare them to my file and determine if i have a winner or not??

First, remember that 4-7-2-8-9 is the same as 2-4-7-8-9, so make sure you always sort your arrays.

Once you are thoroughly comfortable with all the conversion helper functions, you have two options.

  1. Go through the two sorted arrays element by element. If each element of the two arrays are equal, the arrays are equal and you have a winner. Otherwise no.
  2. Convert each array to a string. You're writing that helper function anyway. Might as well use it. Compare the strings with either the == sign or the compare() function from string. If the strings are equal, so are the arrays. This is less work than #1.

>> Once again, i really appreciate your help

No problem. Glad to help.

I don't think anyone has noticed, but the assignment doesn't mention string nor character array anywhere. Where did you get the requirement to convert stuff to a string? Why not just read the values as integers and compare?

i think i need string, because i need to read a line from a file, and i need to compare it to the numbers generated from the program

Why can't you read the line into integer variables? Isn't that allowed?

apparently not. because my professor recommended the same thing.

This is what i have so far.

// strcmp(s1, s2)
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
#include <string>

using namespace std;
//Global Variable
const int MAX_SIZE = 50;
const int SIZE     = 5;

// Function Prototypes
int displayNumbers(fstream&, char[]);
int binarySearch(char[], int, int);
int searchList(int[], int, int);
void displayMenu();
void generateNumbers(int[], int);

int main(int argc, char *argv[])
{
    fstream lottoFile;                              //To read the numbers from a file
    char input[MAX_SIZE];                           //To hold the numbers
    int lottoFoundBinary,
        lottoFoundLinear,
        random_lotto[SIZE],
        choice;
   
  
   // Intro to the program
   cout << "     *LOTTERY WINNERS*\n\n"
        << "This program will tell you if\n"
        << "you are the lucky winner of \n"
        << "$30 million dollars!!\n";
        
    // Menu to show options to determine if the user has the winning combination
    do
    {
    cout <<"\n********** Menu *************\n";
    displayMenu();
    cin >> choice;
        while(choice > 4 || choice < 1)
        {
              cin >> choice;
        }
           if(choice !=4)
           {
            switch(choice)
            {
              case 1: 
                   generateNumbers(random_lotto, SIZE);
                   break;
              case 2:
                   // Perform Binary Search through the variable lottoFoundBinary    
                   lottoFoundBinary = binarySearch(input, MAX_SIZE, random_lotto[SIZE]);
                   break;
              case 3:
                   cout <<"You Chose 3\n";
                   break;
              case 4:
                   cout <<"The program will close now\n";
                   break;
              default:
                   cout << "Select one of the available options:";
              }
            }       
    }while (choice !=4);
      
    system("PAUSE");
    return EXIT_SUCCESS;
}

int displayNumbers(fstream &file, char nums[])
{
 //Open file
 file.open("lottonums.txt",ios::in);
 if(!file)
    {
       cout <<"File Open Error!\n";
       return 0;
    }

    cout <<"This is your lucky combination:\n"
         <<"Reading from file...\n\n";
    
 file.getline(nums, MAX_SIZE);
    while(!file.eof())
    {
       cout << nums << endl;
       file.getline(nums, MAX_SIZE);
    }
    file.close();    
}

int binarySearch(char array[],int numElems,int value) //function heading
{
	int first = 0;				    // First element of list
	int last = numElems - 1;	    // last element of the list
	int middle;					    // variable containing the current 
	int position = -1;              // middle value of the list
	bool found = false;
	
	while (!found && first <= last)
	{
		middle = (last + first) / 2; 
		   
	if (array[middle] == value)
		{
           found = true;
           position = middle;
        }
                                     
	else if (array[middle] > value)
		last = middle - 1;		   // toss out the second remaining half of
								   // the array and search the first 
	else
		first = middle + 1;		   // toss out the first remaining half of
								   // the array and search the second
	}
	
	return position;			   // indicates that value is not in the array
}

int searchList( int List[], int value, int numElems)
{
	for (int count = 0;count <= numElems; count++)  
	{
		if (List[count] == value)
                                                                                // each array entry is checked to see if it contains
	                                                                            // the desired value.
		 return count; 
                                                                                // if the desired value is found, the array subscript
			                                                                    // count is returned to indicate the location in the array
	}
	return -1;	                                                                // if the value is not found, -1 is returned
}

void displayMenu()
{
     cout <<"-----------------------------\n\n";
     cout <<"1. Draw the lotto numbers\n";
     cout <<"2. Perform a Binary Search\n";
     cout <<"3. Perform a Linear Search\n";
     cout <<"4. Quit the program\n";
     cout <<"Enter you choice: ";
}

void generateNumbers(int random_integer[], int arraySize)                                        // Function that calls the random combination
{
system("cls");
cout <<"\nThe Lotto Numbers for today are:\n";


srand((unsigned)time(0));     
    for(int index=0; index< arraySize; index++)
    {
    random_integer[index] = (rand()%49)+1;         
    cout << random_integer[index]
     << ". "; 
    }
    cout <<"\n--------------------------------\n";
    cout << endl <<endl;
}

string toString(int array[], const int array_size)
{
    
}

Can somebody tell me if instead of converting the int to a string, how can i just assign a string instead of the ints to receive the values??

The worst, bar none, worst, thing you can do is take a little bit of advice from me, a little from Walt P, and a little from your professor and try to put them all together and find out later that we all had slightly different approaches, none of which fit with each other. You need to pick one approach and stick with it. You started out the thread asking how to combine numbers into a string. You also said you planned to read the lines in the file into strings. Whether that's a requirement of the assignment or whether that's the avenue you simply decided to go, I don't know. Therefore I figured that your best approach would be to set up helper functions that could easily let you go back and forth between strings and int[] arrays. Once you have those, all your printing, searching, and file reading problems are over. You use whatever you want. When needed, convert.

Can you do the whole thing without ever using a string? Yep. Are you allowed to? I don't know. That's between you and your prof. Can you do the assignment using only strings? No. Is there any reason anywhere to ever have char[] array? I sure don't see one.

You either read the file in as strings and convert to integer arrays or you read the file in directly into integer arrays. The first option makes for much easier reading from the file. The second method saves you from having to write the conversion functions, but requires you to do some serious thought as to how to read the file in and separate the dashes from the numbers from the white space as well as having to write a print routine that loops through an array and sticks dashes in. You're spending time researching and learning to deal with loops and delimiters one way or the other, so I vote to write the int[] to string and string to int[] functions first, get 'em out of the way, then attack the program and use these functions wherever they're beneficial. If you end up writing them and decide not to use them, oh well. You've still learned something.

But the phrasing of the question itself suggests at least to me a lot of confusion about exactly what needs to be done. I think writing the helper functions and having them in your toolset will help crystallize the thinking process.

Can somebody tell me if instead of converting the int to a string, how can i just assign a string instead of the ints to receive the values??

Hi vernon!
okay so this is whats going on, i spent the entire night looking up the string library and im still a little bti confused as far as how to convert the numbers generated to a string. so lemme ask you something else, in my program, the input of the file is copied into a char. how can make it pass it to a string?

void generateNumbers(int random_integer[], int arraySize)                                        // Function that calls the random combination
{
system("cls");
cout <<"\nThe Lotto Numbers for today are:\n";

srand((unsigned)time(0));     
    for(int index=0; index< arraySize; index++)
    {
    random_integer[index] = (rand()%49)+1;        
    }
    cout << random_integer[0] << "-" 
         << random_integer[1] << "-" 
         << random_integer[2] << "-" 
         << random_integer[3] << "-" 
         << random_integer[4]; 
    cout <<"\n--------------------------------\n";
    cout << endl <<endl;

}

And this is the part that im referring to about if i can copy the values of the file to a string rather than a char.

// Function Prototypes
int displayNumbers(fstream&, char[]);
int binarySearch(char[], int, int);
int searchList(int[], int, int);
void generateNumbers(int[], int);
void displayMenu(int, int[], int, char[]);

int main(int argc, char *argv[])
{
    fstream lottoFile;                              //To read the numbers from a file
    char input[MAX_SIZE];                           //To hold the numbers
    int lottoFoundBinary,
        lottoFoundLinear,
        random_lotto[SIZE],
        choice;
            
   // Intro to the program
   cout << "     *LOTTERY WINNERS*\n\n"
        << "This program will tell you if\n"
        << "you are the lucky winner of \n"
        << "$30 million dollars!!\n";
   
   // Display the Menu
   displayMenu(choice, random_lotto, lottoFoundBinary, input);
      
    system("PAUSE");
    return EXIT_SUCCESS;
}

int displayNumbers(fstream &file, char nums[])
{
 //Open file
 file.open("lottonums.txt",ios::in);
 if(!file)
    {
       cout <<"File Open Error!\n";
       return 0;
    }

    cout <<"This is your lucky combination:\n"
         <<"Reading from file...\n\n";
    
 file.getline(nums, MAX_SIZE);
    while(!file.eof())
    {
       cout << nums << endl;
       file.getline(nums, MAX_SIZE);
    }
    file.close();    
}

yeah i tried changing it before and i saw that was the problem. but i cant figure out how to implement it to my code. The getline.function

yeah i tried changing it before and i saw that was the problem. but i cant figure out how to implement it to my code. The getline.function

Not much to it. From the spec...

istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );

You're reading a line, so the default delimiter is '\n', so you don't need to provide one, though you certainly can.

istream& getline ( istream& is, string& str );

I've never tried it with an fstream. I've only tried it with an ifstream. You might want to change your spec from fstream to ifstream. You're not WRITING to a file anyway, so make it an ifstream.

int displayNumbers(fstream &file, char nums[])

to

int displayNumbers(ifstream &file, char nums[])

And get rid of the char[]. It needs to be an int[] or it needs to be a string, depending on just how you're implementing everything. Get all traces of char[] out of your program. They only serve to confuse.

int displayNumbers(ifstream &file, string& str)

Getline would be nothing more than this.

getline(file, str);

But I'll reiterate that I think you're going about this whole process from the wrong direction. I strongly suggest taking a big step back and looking at the program as a whole from an overall design point of view and largely starting over. You cannot read anything from a file until you make a final decision about whether you want to write those helper functions I talked about. You cannot write the function definitions without making those decisions. Without the function definitions, you can't write the functions themselves. To my mind, that means putting the assignment aside and taking a few tutorials so you get much more comfortable with manipulating strings, reading from files, possibly converting from strings to integers and back, etc. Then and only then come back and tackle the assignment.

Not much to it. From the spec...

istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );

You're reading a line, so the default delimiter is '\n', so you don't need to provide one, though you certainly can.

istream& getline ( istream& is, string& str );

I've never tried it with an fstream. I've only tried it with an ifstream. You might want to change your spec from fstream to ifstream. You're not WRITING to a file anyway, so make it an ifstream.

int displayNumbers(fstream &file, char nums[])

to

int displayNumbers(ifstream &file, char nums[])

And get rid of the char[]. It needs to be an int[] or it needs to be a string, depending on just how you're implementing everything. Get all traces of char[] out of your program. They only serve to confuse.

int displayNumbers(ifstream &file, string& str)

Getline would be nothing more than this.

getline(file, str);

But I'll reiterate that I think you're going about this whole process from the wrong direction. I strongly suggest taking a big step back and looking at the program as a whole from an overall design point of view and largely starting over. You cannot read anything from a file until you make a final decision about whether you want to write those helper functions I talked about. You cannot write the function definitions without making those decisions. Without the function definitions, you can't write the functions themselves. To my mind, that means putting the assignment aside and taking a few tutorials so you get much more comfortable with manipulating strings, reading from files, possibly converting from strings to integers and back, etc. Then and only then come back and tackle the assignment.

Vernon Hi!
well i already got the function to return a string instead of char. I already figured out how to convert int to string. Now the part i cant understand is how am i going to store the combination of random numbers in that string without them being the same. For example:
10-23-1-48-21
how do i output the 5 random numbers already converted to a string ???

srand((unsigned)time(0));
for(int index = 0; index < 5; index++)
{
random_integer[index] = (rand()%49)+1;
std::stringstream out;
out << random_integer[index];
randis = out.str();
}

Go back to my first post. You have to write this function. Any stringstreams or whatever that you use will be in this function.

string toString(int array[], const int array_size)

You may even want to write THIS helper function too so that you can convert a SINGLE int to a string.

string toString(int num)

You want your functions to do one thing and do that one thing well. A function that fills in an array with random numbers does just that. It fills in an array. It doesn't convert an int[] array to a string. It doesn't print anything. It fills in the array and lets a different function handle everything else.

As far as how to convert an int to a string and vice versa, there are lots of solutions out there. This one looks decent.

http://www.velocityreviews.com/forums/t283255-string-to-integer.html

As far as converting an ARRAY of ints to a string and vice versa, well it's a matter of converting the individual integers, then either adding dashes or deleting dashes. See earlier posts for some pointers on that.

A function sorts, searches, generates random values, converts, displays, or reads from the file. Again, usually it does ONE thing, and you should give it a name that accurately describes that one thing, and if you have strings, stringstreams, ifstreams, or cout statements in the same function as rand(), the solution is to redesign so you no longer have that.

Go back to my first post. You have to write this function. Any stringstreams or whatever that you use will be in this function.

string toString(int array[], const int array_size)

You may even want to write THIS helper function too so that you can convert a SINGLE int to a string.

string toString(int num)

You want your functions to do one thing and do that one thing well. A function that fills in an array with random numbers does just that. It fills in an array. It doesn't convert an int[] array to a string. It doesn't print anything. It fills in the array and lets a different function handle everything else.

As far as how to convert an int to a string and vice versa, there are lots of solutions out there. This one looks decent.

http://www.velocityreviews.com/forums/t283255-string-to-integer.html

As far as converting an ARRAY of ints to a string and vice versa, well it's a matter of converting the individual integers, then either adding dashes or deleting dashes. See earlier posts for some pointers on that.

A function sorts, searches, generates random values, converts, displays, or reads from the file. Again, usually it does ONE thing, and you should give it a name that accurately describes that one thing, and if you have strings, stringstreams, ifstreams, or cout statements in the same function as rand(), the solution is to redesign so you no longer have that.

okay vernon, im just really confused on how to write the function and what goes inside.

Well I guess if you're completely stuck, I can just give it to you. You'll have to write the conversion function from string to int[] yourself though. Good luck! Can't spend any more time on this.

#include <sstream>
#include <iostream>
using namespace std;


string toString(int num)
{
    stringstream ss;
    ss << num;
    return ss.str();
}


string toString(int array[], const int array_size)
{
    string str = "";
    for(int i = 0; i < array_size; i++)
    {
        if(i > 0)
        {
            str += "-";
        }
        str += toString(array[i]);
    }
    return str;
}


int main()
{
    int array[] = {7, 23, 67, 12, 5};
    string str = toString(array, 5);
    cout << str << endl;
    cin.get();
    return 0;
}

Well I guess if you're completely stuck, I can just give it to you. You'll have to write the conversion function from string to int[] yourself though. Good luck! Can't spend any more time on this.

#include <sstream>
#include <iostream>
using namespace std;


string toString(int num)
{
    stringstream ss;
    ss << num;
    return ss.str();
}


string toString(int array[], const int array_size)
{
    string str = "";
    for(int i = 0; i < array_size; i++)
    {
        if(i > 0)
        {
            str += "-";
        }
        str += toString(array[i]);
    }
    return str;
}


int main()
{
    int array[] = {7, 23, 67, 12, 5};
    string str = toString(array, 5);
    cout << str << endl;
    cin.get();
    return 0;
}

Hi Vernon once again! okay so my program is almost ready. i just cant seem to make the binary and linear search work. i have a menu that prompts he user if he wants to use a binary search or a linear search. But for the linear search i always get that is true regardless of what i do. how could i fix this?

You'll have to start a new thread and post the updated code. This one's gone on for too long, so probably only I am looking at it. If you start a new thread, more people will chime in with help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.