r/learncpp • • Aug 20 '21

Why does this just crash?

Ok, so I am new to C++ and I to help myself learn, I decided to try and remake a program I made in python years ago in C++. But when I try to run this code it just puts a single word on screen, puts nothing on screen or just crashes. Here is my code:

#include <iostream>
#include <conio.h>
#include <time.h>
#include <stdlib.h>

using namespace std;
const string name[] = {"Cian", "Finn", "Niall", "John", "Sam", "Pinn", "Mary", "Gumball", "Bob", "Banana Joe", "Nobody", "Disney", "Samsung", "Google", "BB", "Doge", "Dat Boi", "Chris", "Roxy", "DeeDee", "JJ", "Bonzi", "Peedy"};
const string verb[] = {"rides", "kicked", "ate", "bought", "eats", "broke", "bought and then ate", "killed", "dropped", "sued", "was eaten by", "is eating", "is being sued by", "played", "is playing", "is playing on", "was hit by"};
const string noun[] = {"a lion", "a bicycle", "a plane", "a computer", "a phone", "a tractor","Cian", "Finn", "Niall", "John", "Sam", "Pinn", "Mary", "Gumball", "Bob", "Banana Joe", "a ball", "a fox", "a cat", "a dog", "a banana", "a fidget cube", "a fidget spinner", "an apple", "an Ipad", "a tablet", "a Raspberry Pi", "Google", "Disney", "Samsung", "the phone", "mari0", "Not Pacman", "Chris", "Roxy", "DeeDee", "JJ", "Bonzi", "Peedy"};

int main()
{
    srand(time(NULL));
    rand();
    int num;
    while (true)
    {
        num = rand();
        cout << name[num % sizeof(name)] << " ";
        cout << verb[num % sizeof(verb)] << " ";
        cout << noun[num % sizeof(noun)] << "." << endl << endl;
        getch();
    }
    return 0;
}

I am using Code::Blocks 20.03 on Windows 10 202H with GCC 8.1.0.

4 Upvotes

8 comments sorted by

View all comments

Show parent comment

2

u/jedwardsol Aug 20 '21

https://en.cppreference.com/w/cpp/iterator/size

It's declared in all the headers listed there.

Since you're using std::string you should already be including <string>

2

u/Infinity487 Aug 20 '21

Thanks. Also, when looking at the stuff in the lists, remember that this is a port of something from years ago.