gpt4 book ai didi

c++ - 无法退出无限循环

转载 作者:行者123 更新时间:2023-12-02 10:35:53 24 4
gpt4 key购买 nike

我的程序通过输入任何键开始,然后用户看到颜色变化的文本“欢迎使用我的
现在,用户应该按任意键继续操作,但是他不能退出改变文本颜色的无限循环。为了更好地理解,我向您展示代码。

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");
}
}

最佳答案

这将为您提供解决方案(包括评论)

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

关于c++ - 无法退出无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60344456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com