mercredi 6 janvier 2021

Writing a C++ program to print the letters of a string in a chaotic order

What I'm trying to do is this:

  • User enters a string (For example: "Hello")
  • The program returns the same string, but in a random order(It can be "elHlo" or any other order possible)

So far I've written this code, but the problem is that sometimes the randomly generated numbers are the same, so it might print the same indexes(letters) twice or more times:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    
    cout << "Say something: ";
    string text;
    getline(cin, text);
    
    cout << "\nChaotic text: ";
    
    srand(time(0));
    for(unsigned int j=0; j<text.length(); j++){
        int randomLetter = rand()%text.length(); 
        
        cout << text.at(randomLetter);
    }

    return 0;
}

Can anyone help me fix it?




Aucun commentaire:

Enregistrer un commentaire