Home > front end >  why is the sleep() command not work when I am writing in c
why is the sleep() command not work when I am writing in c

Time:09-03

every time I use sleep() it just says its not recognized:

main.cpp: In function 'int main()':
main.cpp:16.5: error: 'sleep' was not declared in this scope
   16 |    sleep(2);
      |    ^~~~~

I keep looking it up but nothing seems to work

#include < iostream >

using namespace std;

int main()
{
    cout<<"Hello World";
    sleep(2);
    cout<<"hello world";
    return 0;
}

CodePudding user response:

#include <chrono>
#include <iostream>
#include <thread>

using namespace std::chrono_literals;
using std::chrono::system_clock;

auto now_str()
{
    auto now = system_clock::to_time_t(system_clock::now());
    return std::ctime(&now);
}

int main()
{
    std::cout << "Start: " << now_str() << std::flush;

    std::this_thread::sleep_for(2s);
    std::this_thread::sleep_for(200ms);

    std::cout << " Stop: " << now_str() << std::flush;
    return 0;
}

Live demo

CodePudding user response:

To make it work you need to include Windows.h at the beginning.

#include <windows.h>

So your code will look like this:

#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
    cout << "Hello World";
    Sleep(2);
    cout << "hello world";
    return 0;
}

Also in () calling func Sleep(); you enter milliseconds, so if you want to make 2 seconds delay you should enter 2000 like Sleep(2000);, not Sleep(2); because delay will be too short so you won’t even notice it.

  •  Tags:  
  • c
  • Related