c++ - 无法退出无限循环
问题描述
我的程序从输入任何键开始,然后用户会看到一个变色文本“欢迎使用我的程序”。现在,用户应该按任意键继续,但他不能退出改变文本颜色的无限循环。让我向您展示代码以便更好地理解。
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" );
}
}
}
推荐阅读
- google-cloud-platform - BigQuery 如何读取 Google Cloud Storage 中 Parquet 文件的架构?
- python - 奇怪的函数行为(浮点问题)
- python - 如何在使用 matplotlib 绘图时在 x 轴上绘制均匀间隔的值
- c# - 是否可以使用 ASP.NET 从相应的 .cs 文件中定位 .aspx 文件中的 html 元素?
- javascript - 我在 Windows 终端上执行 JavaScript 文件时遇到问题
- php - 如何在 MySQL 查询中包含 PHP 变量
- docker - 如何从 BitBucket Pipeline 启动声纳扫描仪 docker 映像?
- php - 如何在 CI 中检查数据库中的匹配结果?
- opencv - 为什么 cv_bridge 在 ROS Melodic 中使用 OpenCV 3.2?
- arrays - 过滤/跳过缺失的 API 数组结果在 React (Hooks) 中不起作用