why does it say that "sleep(1)" is undefined?

133 views Asked by At

here's the error i got

#ifdef _WIN32
#include <windows.h>
#endif
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    srand((unsigned)time(NULL));
    int random = 1 + rand() % 99;
    int user_input;
    int attempts = 1;

    cout << "random = " << random << endl << endl;
    /* delet this line if you dont want spoilers ^^^ */
    do
    {
        cout << "----------| ";
        cout << attempts << " |----------" << "\n";
        attempts++;
        cout << "guess a random number 1 - 100" << endl;
        cin >> user_input;
        cout << endl;

        if (user_input > random || user_input < random)
        {
            cout << "worng try again" << endl;
        }
    } while (user_input < random || user_input > random);

    cout << "you did it!" << endl;
    cout.flush();
    sleep(1);
    cout << "your prize is";
    cout.flush();
    sleep(1);
    cout << ".";
    cout.flush();
    sleep(1);
    cout << ".";
    cout.flush();
    sleep(1);
    cout << "." << endl;
    cout.flush();
    sleep(1);
    cout << "Nothing!";

    return 0;
}

I was working on a random number guesser at school, and I was using an online C++ compiler, and it was working completely fine. However, when I moved it over to Visual Studio, it said that 'sleep(1)' is undefined, and I don't know how to fix it.

i tried to change _win34 to _win32 but that didn't work and i cant find any replacement for unistd.h. when i ran the code all i got was the same error

2

There are 2 answers

1
David Jones On

The MS UCRT has _sleep() for POSIX compatibility, however it has been deprecated since 2015 in favour of the Windows API Sleep() function.

See Sleep function (synchapi.h).

0
selbie On

Building on the other answer:

Extend your program to be include this function for Win32

#ifdef _WIN32
void sleep(unsigned int seconds) {
    Sleep(seconds * 1000);
}
#end