In C++ and pretty much all other programming languages I know of, arrays use this thing called 0 indexing. That means the index of the elements starts counting from 0. The first element is indexed 0, second 1, and so on. If you have an array of size n the last element is indexed n - 1.
In your code, the array test
has a size of three. The elements have index 0, 1, and 2. Your loop goes from 1 to 3, so the last time in the loop you tried to access the element past the end of the array, causing an access violation. You should instead loop from 0 to 2 like this:
for(int i = 0; i < 3; i++)
By the way, there are a lot of other problems in your code:
You never set the seed for rand()
, so every time you run the program it will output the same thing.
You used rand() % 4
to generate random numbers, which will give you numbers from 0 to 3, therefore, ignoring the last word.
The last if statement makes no sense at all since you are checking if guess is equal to 3, which it will never be (it must be larger than 3 for the loop to break), and then you tried to output the whole array words
, which does not work. You should use a loop to output each element of test
not guess
.
Code with all the changes:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
// set the seed for rand() using the current time
std::srand(std::time(nullptr));
std::string words[5] = {"Me", "You", "Everyone", "Mom", "Dad"}, test[3];
for(int i = 0; i < 3; i++)
{
test[i] = words[std::rand() % 5];
}
for(int i = 0; i < 3; i++)
{
std::cout << test[i] << " ";
}
std::cout << '\n';
}
I would recommend getting a good book.
You can merge the two loops without even storing the words guessed:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
// set the seed for rand() using the current time
std::srand(std::time(nullptr));
std::string words[5] = {"Me", "You", "Everyone", "Mom", "Dad"};
for(int i = 0; i < 3; i++)
{
std::cout << words[std::rand() % 5] << ' ';
}
std::cout << '\n';
}
Note that in general, using the std::rand()
function is not recommended since it tends to result in low quality random numbers. It is best to use the newer random number generators in the standard library instead.