gpt4 book ai didi

c++ - 如何使用用户输入打破循环?

转载 作者:行者123 更新时间:2023-11-30 05:32:23 28 4
gpt4 key购买 nike

我正在尝试这样的事情。它从 5-1 开始倒计时。

 #include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<iomanip>
using namespace std;

int main()
{
for(int i=5;i>0;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
system("PAUSE");
}

我试图找出一种方法来打破循环,使用用户输入(从键盘)在它运行时打破它。我不知道该怎么做。我听说过多线程。我什至不知道多线程在我的情况下是否有任何应用。那么关于如何在执行循环时在中间中断它有什么想法吗?

最佳答案

我想你需要一个线程来完成它。

在主循环中添加一个全局变量,使用线程接收命令行输入并修改您的全局变量。

声明一个全局变量

bool stop = false;

创建一个线程来读取stdin并修改'stop'

DWORD WINAPI thread1(LPVOID pm)
{
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
return 0;
}

在你的主要:

HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}

关于c++ - 如何使用用户输入打破循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144822/

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