• 周六. 5月 3rd, 2025

C语言入门 — while语句

2月 15, 2020

C语言入门,while语句,实现在一定条件下的循环,可以用while实现死循环,while的使用语法如下:

while(执行条件)
{
    执行代码;
}

1、使用while,实现死循环,死循环一般在新建进程或者线程的时候经常会用到,下面举个使用while实现1秒打印一次的程序

#include <stdio.h>
int main(void)
{
    while(1)
    {
        printf("Test.\n");
        sleep(1);
    }
    return 0;
}

运行结果:

Test.
Test.
Test.

以上程序会每隔一秒打印一次Test.

2、在while里加上判断条件

#include <stdio.h>
int main(void)
{
    char a;
    a = getchar();                           //从标准输入获取字符
    while(a != 'c')                          //当遇到c字符输入,退出循环。
    {
        if(a != '\n')                        //从获取的字符里滤掉回车键
            printf("You type:%c,not c\n",a);
        a = getchar();
    }
    printf("Got c.\n");
    return 0;
}

运行结果:

q
You type:q,not c
c
Got c.

该程序,一开始等待键盘输入,获取输入之后,使用while进行判断,如果输入的不是c字符,则进入循环,并打印输入的字符。然后继续等待键盘输入,直至遇到c字符的输入。