可以将整个程序放在一个死循环内部,这样就可以不断地输出随机字符了,修改后的代码如下:

#include #include <stdlib.h> #include <time.h> #include <windows.h>

using namespace std;

int main() { srand(time(NULL)); // 初始化随机数种子

while (true) { // 死循环
    int length = 100; // 生成字符的数量
    int color; // 存储随机生成的颜色

    // 循环生成字符
    for (int i = 0; i < length; i++) {
        char c = rand() % 256; // 生成随机字符
        color = rand() % 15 + 1; // 生成随机颜色
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // 获取控制台句柄
        SetConsoleTextAttribute(hConsole, color); // 设置控制台输出的颜色
        cout << c; // 输出字符
    }
    cout << endl; // 输出换行符,让每次输出在新的一行

    Sleep(50); // 睡眠50毫秒,让输出速度变慢,方便观察
}

return 0;
#include iostream#include stdlibh#include timeh#include windowshusing namespace std;int main srandtimeNULL; 初始化随机数种子 while true 死循环 int length = 100; 生成字符的数量 int color; 存储随机生成

原文地址: https://www.cveoy.top/t/topic/dHV0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录