简体   繁体   中英

string Iteration delay by 200ms

Someone can tell me what is wrong with this code?

I want to show 'a' with 200ms delay eg. number 3 will show after 200ms numbers 2 and 1 the same, but I can't write correct code to do this.

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

using namespace std;

int main() {
    int a=3;
    do {
        cout<<a<<endl;
        a-=1;
        string tekst = a;
        for (int i = 0; i < tekst.length(); i++) { // Czasowe pokazanie napisu//
            cout << tekst[i];
            cout << tekst[i];
            Sleep(200);       
        }
    }
    while (a=1);
    getch();
}

I want to show 'a' with 200ms delay eg. number 3 will show after 200ms numbers 2 and 1 the same, but I can't write correct code to do this.

In that case, your Sleep is misplaced since it's placed after printing. You also do not need to convert the int to a std::string before printing it. int s are perfectly streamable out of the box.

Your do-while loop is also wrong. while (a=1); assigns the value 1 to a so the loop will go on forever since 1 will be implicitly converted to true .

A portable way to sleep 200 ms would be using the std::this_thread::sleep_for() function instead of Sleep() which is not a standard function.

It could look like this:

#include <chrono>    // std::chrono::milliseconds
#include <iostream>
#include <thread>    // std::this_thread::sleep_for

using namespace std::chrono_literals;

int main() {
    for(int a=3; a>0; --a) {
        // sleep for 200 ms, the standard way
        std::this_thread::sleep_for(200ms);

        std::cout << a << std::flush;
        // or: std::cout << a << '\n';
    }
}

Update for old versions of Dev C++ that doesn't support <thread> and <chrono> :

#include <iostream>

int main() {
    for(int a=3; a>0; --a) {
        Sleep(200);

        std::cout << a << std::flush;
        // or: std::cout << a << '\n';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM