0
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
#include <stdlib.h>
#include <time.h>





using namespace std;  


int main()
{
    string Alphabets[26] = { "Hey","How","Are","you","Doing","Today","My","Name",
"Is","John","Its","Great","to","finally","meet","you","today",
"wow","summer","was","long","school","has","started","now"};
    string RandString[20];
    srand(time(NULL));

    for (int k = 0; k < 20; k++) {
        int temp = rand() % 26;
        RandString[k] = Alphabets[temp];
    }

    for (string RandomString : RandString ) {
        cout << RandomString << endl;
    }

    for (int i = 20; i >= 0; i--) {
        cout << RandString[i] << endl;
    }

}

I'm having trouble understanding my code to an extent. Right now, my code is randomly generating 20 strings into an array. I have one range for loop that shows the strings that we're picked by the random string generator. But my issue comes with the last part of the code and that is to reverse it. I believe what I'm doing wrong is that I'm trying to reverse strings that haven't been randomly generated yet. Therefore, I believe that's why nothing appears, and if this is the case, I have forgotten how to take an array that's been fully populated and then assign it to a different variable which 'I think also has to be an array'. I know this is a silly question but could someone tell me why, if this array isn't being populated when called outside of the for loop why is the ranged for loop able to then print it out?

John
  • 1
  • 6
    Your last loop first tries to pring `RandString[20]` which is out of bounds. – François Andrieux Aug 24 '22 at 15:00
  • Notice you only initialize `string Alphabets[26]` with 25 strings, so the last one is just an empty string. Sometimes you will get empty strings in your output. – François Andrieux Aug 24 '22 at 15:02
  • [C++11 reverse range-based for-loop](https://stackoverflow.com/questions/8542591/c11-reverse-range-based-for-loop) is an interesting read if you like range based loops. – Retired Ninja Aug 24 '22 at 15:06
  • The interesting thing about random data is no one can really tell if it's been reversed or not... – user4581301 Aug 24 '22 at 15:35
  • When you initialize an array please don't specify the size `string arr [] = {...}` to avoid empty entries - compiler will automatically set the size. Then you can take it's length with `sizeof(arr)/sizeof(arr[0])`. Even better if you use an std::array. – Bartosz Charuza Aug 24 '22 at 17:36

0 Answers0