-4

I'm learning C++ and was told to make a horse racing game for class. I've mostly finished it, it prints a horse, and moves it if a random number is over 5, then waits a moment, clears the screen, and repeat. However, whenever I have the system("cls"); added, it completely breaks the program. Can someone figure out what has gone wrong?

code:


#include <iostream>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include <cstdlib>
using namespace std;
void horse(int &p);

int main()
{
    srand((unsigned) time(NULL));

    int p=0;
    do{
    system("cls");
        horse (p);
        Sleep(250);

    }while (p<20);
    

}
void horse (int &p)
{
    for (int i;i<20;i++)
        if (i==p)
            cout<<"#";
        else
            cout<<"-";
        cout<<endl; 
        if (rand()%11>5)
            p++;
    

    
}

for clearscreen to clear off my horse, instead it completely breaks my program

  • 4
    What does "breaks my program" mean? – pm100 Jan 09 '23 at 17:13
  • when the clearscreen is added, it clears the screen, and then the program no longer outputs anything, until it completely closes. – Mental-Breakdown Jan 09 '23 at 17:14
  • I was not aware that cls was a stand alone program. – Arthur Kalliokoski Jan 09 '23 at 17:20
  • 3
    The bug is not caused by `cls`, but by the fact that the `int i` variable within the body of the function `horse` is never initialized, which causes [undefined behaviors](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). – kotatsuyaki Jan 09 '23 at 17:22
  • 2
    `system("cls")` is unfortunately a common [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern), and often part of [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming). Neither are very good. – Some programmer dude Jan 09 '23 at 18:10

1 Answers1

1

The problem is, you are not initializing the variable i, so, your loop never runs correctly thus nothing is appearing on the screen. To fix it change:

    for (int i; i<20; i++)

to

    for (int i = 0; i<20; i++)
Cyao
  • 727
  • 4
  • 18