I think I have corrected most of the errors, but still have some questions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX =10;
class Baz
{
public:
int number;
std::string name;
};
class Foobar
{
public:
Baz bar[MAX];
Foobar()
{
int random;
for (int j=0; j < MAX; j++)
{
//GIVE VALUE OF 'random' TO 'bar[].number'
random = rand()%1000-9999;
bar[j].number = random;
}
}//END constructor Foobar()
void newBaz()
{
int random;
bool isPresent = false;
do
{
// random = rand()%1000-9999;
//CHECK IF VALUE OF 'random' IS PRESENT IN 'bar[].number'
for(int i=0; i < MAX; i++)
{
//IF VALUE IS PRESENT
if(bar[i].number == random)
{
//GIVE 'random' NEW VALUE
random = rand()%1000-9999;
//CHECK AGAIN
isPresent = true;
}//END if
}//END for
}while(isPresent)
// bar[0].number = random;
std::cin >> bar[0].name;
}//END newBaz()
};
int main()
{
srand(time(0));
Foobar qux;
qux.newBaz();
}
|
Do you mean: Replace it by a new one? Then your code is wrong. It ever replaces only the first number of your array |
I want the value of 'random' to be replaced if the number given to it allready exists within the array, thus every number in the array must be unique.
I'm not sure what you mean? This is what I want it to do
-Iterate through the array
-If a number in the array is equal to the random number
-Change the random number(not the number in the array)
-Iterate again to make sure the new random number isnt present
-If the random number is unique
-Give the random number to the array object number-spot and continue program.
Please give us more than an hour to respond. There aren't necessarily people on here 24/7. |
Sorry for the bump, wont happen again
I suggest you replace "sizeof()" with 10 |
I did put the
const int MAX;
variable there instead. This should work just as fine? The reason is if the value is changed, the easy way is to just having to change it once at one location.
Also, use a for loop or some other loop to initialize the values in your array of objects |
As soon as I run the program, the objects are created from main(dont know why, but they are) and if I'm not wrong there should be pregenerated numbers inside the arrays?
EDIT
Added thejman250's constructor(or parts of it)
The reason I dont want to use
std::cin
in the constructor is because when the program starts, it creates the objects, and the user should not have to enter the names at the beginning of the program. Correct me if I'm wrong.
But the idea of generating the random numbers in the constructor is a great.