0

So, I'm trying to replicate a simple dice roll using cstdlib and rand(), but visual studio code seems to have a problem with rand, claiming it's not defined, despite me having included cstdlib, any thoughts?

i'll paste the code, as bare bones as it is atm, perhaps someone could figure it out? FYI, I'm using Visual Studio Code on PopOS 20.10 (not sure if it's relevant)

#include <iostream>
#include <cstdlib>
#include <random>

class player
    {
        public:

            std::string name;
            int health;
            int strength = 1 + (std::rand() % 12);
            int defense;
            int initiative;
            int luck;

            void levelup();

            void win();

            void lose();

        private:   

    };

The error it throws up is: namespace "std" has no member "rand" C/C++(135)

Kari
  • 1
  • 2
  • 1
    [Works for me](https://godbolt.org/z/84xPxK). You should include the complete error message you see, it might give a clue as to what is really going on. – john Nov 26 '20 at 11:12
  • Unsure of it, but C defines `rand` while C++ defines `std::rand`. Using `rand` along with `using namespace std;` might confuse a not too clever compiler. – Serge Ballesta Nov 26 '20 at 11:14
  • if i make it: int strength = 1 + (std::rand() % 6); it then gives me: namespace "std" has no member "rand" C/C++(135). Actually, if i take out using namespace, string name throws up a problem, so i add std::string, and its fine. yet std::rand() still has a problem – Kari Nov 26 '20 at 11:17
  • first [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) then try what @Serge Ballesta wrot – yaodav Nov 26 '20 at 11:17

1 Answers1

0

so the issue was in that in /usr/include/c++/10/tr1/cstdlib the file contents didn't use rand, srand etc...

there was a decent copy in /usr/include/c++/10/cstdlib, which had references to rand and srand.

i probably have to copy all the files from /include to /include/tr1, since that's where VSC seems to be looking, otherwise i'll have to try edit my include path, do exclude tr1.

for now, i've just copied /usr/include/c++/10/cstdlib to /usr/include/c++/10/tr1/cstdlib, restarted VSC and viola, worked.

Kari
  • 1
  • 2
  • Glad you got it sorted but copying system header files around sounds like a recipe for future problems. You should be editting your compiler configuration so that it looks in the correct place. – john Nov 26 '20 at 12:22
  • agreed. not sure why it wasn't looking there in the first place. i'll see if i can figure that one out. thanks for the support! – Kari Nov 26 '20 at 12:30