首页 > 解决方案 > 无法退出无限循环

问题描述

我的程序从输入任何键开始,然后用户会看到一个变色文本“欢迎使用我的程序”。现在,用户应该按任意键继续,但他不能退出改变文本颜色的无限循环。让我向您展示代码以便更好地理解。

HANDLE color=GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"Press any key to start...";
int stop=getchar();
while(stop){
    for(i=10;i<=15;i++){
        cout <<("\n\t\t\t\t\t Welcome to my program\n");
        SetConsoleTextAttribute(color,i);
        Sleep(100);
        system("cls");
    }
}

标签: c++textcolorsinfinite-loop

解决方案


这将是您的解决方案(包括评论)

#include <iostream>
#include <Windows.h>
#include <thread>

int main()
{
    HANDLE color = GetStdHandle( STD_OUTPUT_HANDLE );
    std::cout << "Press any key to start...";
    bool stop = false; // use a Boolean instead of int 
    // doesn't really matter what the input is, so use getchar().
    // Note, this is really just "enter". You can modify if you expect user to 
    //   hit multiple keys before hitting enter
    getchar(); 

    // This line here will start a new thread which will wait for the user to hit enter
    std::thread getInput = std::thread( [&stop] { getchar(); stop = true; } );
    // Loop stays the same (except I inverse the "stop" variable to make more sense)
    while ( !stop ) {
        for ( int i = 10; i <= 15; i++ ) {
            std::cout << ( "\n\t\t\t\t\t Welcome to my program\n" );
            SetConsoleTextAttribute( color, i );
            Sleep( 100 );
            system( "cls" );
        }
    }
}

推荐阅读