I am brand new to C++ and working on a homework assignment (just need to get past this hump). I have a function that is working with an array of 3 numbers. I'm trying to generate a random digit for each slot in the array, under 10. Here is my function:
You created an array of strings, which you're trying to output - so 0x27fe20 is the address of the first element in the array.
What you actually wanted is this: string cpDigits(SIZE);
This creates a single string with an initial size of 3.
cpDigits[i] = (rand()%10); doesn't do what you want either. If you look at an ASCII table, you'll see entries 0-9 aren't printable characters. cpDigits[i] = rand()%10 + '0'; will work.
Those are just hexadecimal numbers (base 16). 0x27fe20 is 2620960 in decimal form (base 10). Put srand(time(NULL)); in your main function, not in getSecretDigits() You also really don't need a seperate function for this. Just something like this should work fine:
Athar, I have declared the array with this: string cpDigits[SIZE];
Is that different than what you are suggesting?
Also, adding the + '0' did not change the result and I'm not sure I understand how it would?
In any case, I tried your suggestions and it wouldn't run. I got a compiler error.
ascii, I would love to ditch the function, but it's part of the assignment. I did change the placement of srand, but nothing changed. I also tried this and still got the exact same result:
Your function returns a string. I think the idea is to fill ONE string with the digits, not an array of them.
Something like this may work better in your function:
1 2 3
string cpDigits;
for(int i=0;i<SIZE;++i)
cpDigits += rand()%10 + '0';// add the digits to the string one by one
Have your function return this string then print it out in main: cout << getSecretDigits();
You could print it in the function also, as you were trying to do, but I'd guess that the intent is to make use of the functions return value in main().
P.S. How are Shrek and the kids? (couldn't resist)
Does the function have to return a string? If it doesn't you can just make it a void function. If you declare the array in main() and pass it as a parameter then you just have to put random numbers in the three slots and you're set.
If you have to return a string then you don't even need an array do you? You can just use the += operator to add the random digit. Just don't forget as the other too posted to add the '0' to convert it to an ASCII value :)
Thank you so much guys! My friend told me to use an itoa function but it was beyond my understanding. The teacher suggested working with the ASCII table by using numbers between 48 and 57, which was annoying to do. I did what you said fun2code and it worked!