I want to ask how can I print the word Chessmaster in 2d array randomly each letter of the word? I tried with srand but I don't how to combine it with characters. Can someone help me with is code. Also, can I create random letters in a 2d array without rand?
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX = 11;
using namespace std;
void printwo()
{
char word[MAX] = {'c', 'h', 'e', 's', 's', 'm', 'a', 's', 't', 'e', 'r'};
int c, i, n, letters;
cout << "I will print this word " << word << " sepereate" << endl;
srand(time(NULL));
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[i] << "]"
<< "["
<< "]";
cout << endl;
}
}
}
int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;
if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
exit(0);
}
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX = 11;
using namespace std;
// Generate a random number between min and max (inclusive)
// Assumes std::srand() has already been called
// Assumes max - min <= RAND_MAX
int getRandomNumber(int min, int max)
{
static constexpr double fraction { 1.0 / (RAND_MAX + 1.0) }; // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}
void printwo()
{
char word[MAX+1] = {"chessmaster"}; //If you are using C-style strings then you should declare +1 space
//int c, i, n, letters; not needed
cout << "I will print this word " << word << " sepereate" << endl;
//srand only gives a seed to yout tand function, you need to call std::rand() to get a random integer
//use the function getRandomNumber above that is based on rand() and gives you the possibility to select range
srand(time(NULL));
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[getRandomNumber(0,10)] << "]"
<< "["
<< "]";
cout << endl;
}
}
}
int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;
if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
//exit(0); exit here not needed
}
return 0;
}
I wrote some comments.. please read them and ask me if you don't get something. I would suggest reading about C-style strings and rand() here: Rand() - https://www.learncpp.com/cpp-tutorial/59-random-number-generation/ C-style strings(basically arrays of char) - https://www.learncpp.com/cpp-tutorial/66-c-style-strings/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.