Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 随时退出循环_C - Fatal编程技术网

C 随时退出循环

C 随时退出循环,c,C,我试图在任何时候按任意键退出循环。我尝试了下面的代码,但无法完成。我需要你的帮助。先谢谢你。我使用的是C-Free5.0 #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int b=0, i; int seconds; printf("\nEnter number of seconds : "); scanf("%d", &am

我试图在任何时候按任意键退出循环。我尝试了下面的代码,但无法完成。我需要你的帮助。先谢谢你。我使用的是C-Free5.0

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

int main(void)
{
    int b=0, i;
    int seconds;
    printf("\nEnter number of seconds : ");
    scanf("%d", &seconds);
    while (b==0)
    {
        for(i=1;i<=seconds;i++)
        {
            time_t end = time(0) + 1;
            while(time(0) < end)
            ;
            seconds -= 1;
            printf("Number of seconds left : %d\n", seconds);
            b=kbhit();
        }

        if(seconds == 0)
        {
            exit(0);
        }
    }
    printf("Number of remaining seconds left : %d\n", seconds);
}
#包括
#包括
#包括
内部主(空)
{
int b=0,i;
整数秒;
printf(“\n输入秒数:”);
扫描频率(“%d”,秒(&S);
而(b==0)
{

因为(i=1;i你在“忙着等待”这可能不是最好的解决方案,但如果这是你想做的,你需要在那个循环中添加一个测试来检查一个键是否被击中。< /p> 退出循环使用C++中的一个函数称为KHBIT。当任何键被按下并变空时,它会变为1,并重新分配使用GECHH()/P>键清除缓冲区的键。
#包括
#包括
使用名称空间std;
int main()
{
而(1)
{
if(kbhit())//khbit将在输入键时变为1。
{
break;//将中断循环
}
//尝试使用一些延迟,比如sleep(100);//睡眠10秒以避免CPU压力
}
//如果要再次使用khbit,则必须通过char dump=getch()清除它;
//这样,您也可以决定按哪个键
//如果(转储==“A”)

//{coutWhat确切地说是“C-Free 5.0”?如果这是一些晦涩难懂的C编译器,你可能最好切换到gcc(如果你在Windows上,则为mingw)。可能是重复的哦,等等,你已经看到这个问题了吗?kbhit?O_OAwesome…!!我知道了…非常感谢。
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())  // khbit will become 1 on key entry.
        {
            break;    // will break the loop
        }

                     // Try to use some delay like sleep(100);  // sleeps for 10th of second to avoid stress on CPU
    }

                     // If you want to use khbit again then you must clear it by char dump = getch();

                     // This way you can also take a decision that which key was pressed like 

                     // if(dump == 'A')

                     //{ cout<<"A was pressed e.t.c";}
}