I'm very new to c++ and this looks correct to me.
Ok, so let me tell you something: in C++ we don't use C style arrays. Period. If you really want fixed sized arrays use std::array
. If you want something more dynamic: use std::vector
. If you want fixed size array of bool
, use std::bitset
, and if you want it dynamic, use boost::dynamic_bitset
.
But when run, I get 1 and then 0 display?
Of course you do. The %
(modulus) operator will return the remainder of the division between the left and right hand side. For example: 3 % 2 = 1
and 2 % 2 = 0
. In your example, since 2 % 2 = 0
, rand() % 2
will always return either 0
or 1
(never 2
); which is perfect, since your array only contains 2 elements of index 0
and 1
.
If what you meant is to have an array until the 2
nd index, then you meant to declare an array of 3 items:
std::array<std::string, 3> quotes;
and then define the "randomizer" to:
std::cout << quotes[rand() % 3] << " " << std::endl;
Also, please, take a look at this answer that will point to you to the flaws of using rand()
with the modulus operator, and how to fix them.