首页 > 解决方案 > 字符串迭代延迟200ms

问题描述

有人可以告诉我这段代码有什么问题吗?

我想以 200 毫秒的延迟显示“a”,例如。数字 3 将在 200 毫秒后显示数字 2 和 1 相同,但我无法编写正确的代码来执行此操作。

#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();
}

标签: c++

解决方案


我想以 200 毫秒的延迟显示“a”,例如。数字 3 将在 200 毫秒后显示数字 2 和 1 相同,但我无法编写正确的代码来执行此操作。

在这种情况下,您Sleep的位置是错误的,因为它是打印后放置的。您也不需要在打印之前将其转换int为 a 。s 是开箱即用的完美流媒体。std::stringint

你的do-while循环也是错误的。while (a=1);将值分配给1a因此循环将永远持续下去,因为1将隐式转换为true.

睡眠 200 毫秒的便携式方法是使用该std::this_thread::sleep_for()函数,而不是使用Sleep()它不是标准函数。

它可能看起来像这样:

#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';
    }
}

更新不支持<thread>和的旧版本的 Dev C++ <chrono>

#include <iostream>

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

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


推荐阅读