Reputation: 21
So I'm trying to test something out to see how rand() works in c++! I'm very new to c++ but I'm wondering how can I get the following code to print out either the letter B or A when the number 1 or 2 is generated?? the code ask if he wants to generate a letter, enter y for yes or n for no! then a letter generates but it seems to only generate the letter A?? any idea?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
char x;
char d;
cout << "generate random letter?(y/n)" << endl;
cin >> x;
if (x = 'y'){
srand(time(NULL));
int randNum = (rand() % 2) + 1;
if (randNum = 1){
d = 'A';
}
else {
d = 'B';
}
cout << d << endl;
}
else{ return 0; }
system("pause");
}
Upvotes: 1
Views: 481
Reputation: 166
There's a much easier way to generate a random char. Chars can be created from an ASCII code number since we know from uppercase A to lowercase Z is in the range of 65-122 (google ASCII table)
std::random_device rd;
std::mt19937 engine(rd());
std::uniform_int_distribution<int> dist(65, 122);
char ascii_char = dist(engine);
std::cout << scii_char;
as a side note, std::uniform_int_distribution dist(65, 122) is inclusive, so it includes both 65 and 122.
Upvotes: 0
Reputation: 326
When you say:
if(randNum = 1)
you assign the value 1 to randNum
, then check if it is True
. In C/C++ any non-zero number is True
. In this way you always enter the first part of the if
statement and get an 'A'.
Instead if you say:
if(randNum == 1)
you are comparing randNum
to 1
and will get the behavior you want.
Upvotes: 0
Reputation: 42934
In modern C++, rand()
is deprecated, and other techniques based on e.g. mt19937
Mersenne twister engine and uniform_int_distrubtion
are used.
You may want to consider some code like this:
#include <iostream> // For console output
#include <random> // For pseudo-random number generators and distributions
int main()
{
// Use random_device to generate a seed for Mersenne twister engine.
std::random_device rd;
// Use Mersenne twister engine to generate pseudo-random numbers.
std::mt19937 engine(rd());
// "Filter" MT engine's output to generate pseudo-random integer values,
// **uniformly distributed** on the closed interval [0, 1].
// (Note that the range is [inclusive, inclusive].)
std::uniform_int_distribution<int> dist(0, 1);
// Print 20 pseudo-random letters (A, B).
for (int i = 0; i < 20; ++i)
{
// Generate pseudo-random number
if (dist(engine) == 0)
{
std::cout << 'A';
}
else
{
std::cout << 'B';
}
std::cout << ' ';
}
std::cout << std::endl;
}
Upvotes: 0