mardi 2 novembre 2021

How to shuffle an array in C++?

I have an array:

names[4]={john,david,jack,harry};

and i want to do it randomly shuffle, like:

names[4]={jack,david,john,harry};

I tried to use this but it just shuffled the letters of the first word in the array:

random_shuffle(names->begin(), names->end());

Here is the full code, it reads names from a .txt file and puts in an array:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;


int main() {

    ifstream readName("names.txt");
    string names[197];
    int i = 0;
    for (string line; getline(readName, line); ){
        readName >> names[i];
        i++;
    }
    readName.close();


    random_shuffle(names->begin(), names->end());
    
    for (int i = 0; i < 197; i++) {
        cout << names[i] << endl;
    }
    return 0;
}

I tried few other things from different people but I couldn't manage to work it.. Anything helps, thank you!




Aucun commentaire:

Enregistrer un commentaire