C语言进阶:循环语句while

1、基础用法,例:输出1~10。

#include <stdio.h>
int main()
{
	int i = 1;

	while (i <= 10)
	{
		printf("%d \n", i);
		++i;
	}

	return 0;
}

2、getchar()获得一个字符,putchar打印这个字符。

**形如 scanf getchar()这样的输入指令并非直接从键盘上获得数据,而是通过键盘将数据给到缓冲区,再从缓冲区获得数据,而scanf不会拿走\n,这就会导致这两个一起用的时候会出现bug。

#include<stdio.h>
int main()
{
	int passerword[20] = {0};
	scanf("%d ", passerword);
	int ch = 0;
	while ((ch = getchar()) != '\n')
	{
		;
	}
//这个while循环刚好解决了getchar会被\n限制的问题。
	printf("请确认您的密码(Y/N):");
	int i = getchar();
	if (i == 'Y')
	{

		printf("Yes\n");
	}
	else
	{

		printf("No\n");
	}

	return 0;
}

3、continue会跳过本次循环后面的代码,并从头开始来检验是否符合条件。

#include<stdio.h>
int main()
{
	int ch = 0;
	while ((ch = getchar()) != EOF)
//EOF是getchar()的返回值,这样就形成了一个循环。
	{
		if (ch < '0' || ch>'9')
//如果不是数字那么他就会被continue截住而不输出。
			continue;
			putchar(ch);

	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值