The for loop on lines 17-24: Looks to me like you wanted to shuffle the letters array. Change the loop variable to just go from 0 to 500 or maybe 0 to 1000, and I would consider renaming the loop variable to something like iteration. Then inside the loop create random integers i and j with rand() % g, then swap letters[i] with letters[j]. After 500 or 1000 iterations of swapping two random locations it should be shuffled.
Edit: g is not a very informative variable name; you should consider renaming it to something like letters_size.
Edit Edit: See Thomas1965's post about random_shuffle
im not sure if that was addressing my question. when i make an array of six names it prints out in random order everytime with no problem. i wanted to be able to take input of six names and print that out. and i cant tell if thats what their code does.
#include <iostream>
#include <string>
#include <algorithm>
#include <ctime>
usingnamespace std;
int main() {
constint g = 6;
srand(time(0));
string strings[6];
cout << "Enter 6 strings." << endl;
//get the strings from user input
for (int i = 0; i < g; i++)
{
getline(cin, strings[i]); //Fill each string in the array with user input
}
cout << "Randomizing string order..." << endl;
//Randomly swap the strings in the array to randomize string positions
for (int i = 0; i < g; i++)
{
int index = rand() % g;
swap(strings[i], strings[index]);
}
cout << "Printing strings..." << endl;
//Print out the strings
for (int i = 0; i < g; i++) {
cout << strings[i] << endl;
}
system("pause");
return 0;
}
The better question is why would you use a while loop for the inputs?
You only have an array of size 6, so that's why I used a for loop since you can only input 6 strings. If I used a while loop, it could go out of bounds.
If I used a while loop, it could go out of bounds.
It would go out of bounds only if your condition is bad.
The while and for are almost the same:
1 2 3 4 5 6 7 8 9 10 11 12
int i = 0; // init
while ( i < g ) { // cond
std::cout << strings[i] << '\n';
++i; // incr
}
// OR
for ( int i = 0; // init
i < g; // cond
++i ) { // incr
std::cout << strings[i] << '\n';
}
The choice between the two may depend on the tiny differences, or what impression the coder wants to give to the reader.
The 'for' tends to imply that we know how many times we will iterate.
The 'while' tends to imply that we do not know how many times we will iterate.
The ranged for syntax for ( constauto & word : strings ) std::cout << str << '\n' ;
iterates exactly every item in a range (unless the body has a conditional break ...)