Bob
Bob

Reputation: 1396

C++: cout statements making my program go haywire?

#include <iostream>
#include <string>
#include <random>
#include <Windows.h>
using namespace std;


    int playerHP = 20;
    int enemyHP = 20;
    int playerAtk =(rand()%4 + 5); //Find a random number between 5 and 8
    int playerDef = (rand()%4 + 5);
    int playerAgi = (rand()%4 + 5);
    int enemyAtk = (rand()%4 + 4); //Find a random number between 5 and 7
    int enemyDef = (rand()%4 + 4);
    int enemyAgi = (rand()%4 + 4);
    cout<<"---------------"<< endl; // what in the sam hill is going on
    cout<<"FIGHTER STATS"<< endl;
    cout<<"----------------"<<endl;
    cout<<"Player Stats:"<<endl;
    cout<<"HP "<<playerHP<<endl;
    cout<<"ATK "<<playerAtk<<endl;
    cout<<"DEF "<<playerDef<<endl;
    cout<<"AGI "<<playerAgi<<endl;
    cout<<"ENEMY STATS:"<<endl;
    cout<< "HP "<<enemyHP<<endl;    
    cout<<"ATK "<<enemyAtk<<endl;
    cout<<"DEF "<<enemyDef<<endl;
    cout<<"AGI "<<enemyAgi<<endl;

I can't seem to figure out why my cout statements are creating so many bugs in my program. This is obviously not my whole program, but I wanted to keep things short and sweet. I am getting the errors C2143:syntax eerror : missing ';' before '<<', C4430: missing type specifier-int assumed, and C2086 'int cout':redefinition on almost all of my cout statements and I can't figure out why. Thanks for any and all help and please dumb things down as much as possible, this is my first C++ program ever.

Upvotes: 0

Views: 289

Answers (1)

simonc
simonc

Reputation: 42185

Assuming you've posted exactly the code you're trying to compile, statements like

cout<<"---------------"<< endl;

need to be inside a function.

Earlier lines wouldn't have caused an error as its valid to declare variables with global scope outside of any function. It isn't great practice to do this though and you certainly shouldn't make variables global if they're just required by a single function.

Try moving all your code into a main function. i.e.

int main()
{
    int playerHP = 20;
    int enemyHP = 20;
    int playerAtk =(rand()%4 + 5);
    // rest of your code goes here
}

Once you get your code compiling and running, you'll find that your random numbers are always initialised to the same values. You need to call srand, choosing a value that varies between runs, before calling rand. The current time is an easy seed to choose if you don't mind that it only changes once per second

int main()
{
    int playerHP = 20;
    int enemyHP = 20;
    srand(time(NULL));
    int playerAtk =(rand()%4 + 5);

Upvotes: 3

Related Questions