C语言学习————循环语句while

C语言中有三种循环:

while循环

do while循环

for循环

while循环

语法结构

表达式成立(为真),循环语句就会执行。

例子:用while循环打印从一到十

int main()
{
	int i = 1;
	while (i <= 10)
	{
		printf("%d\n",i);
		i++;
	}
	return 0;
}

到这里已经学会了while循环的基本语法。

while循环中,break的用法

例:

int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			break;//在while循环中,break用于永久的终止循环。
		printf("%d", i);
		i++;
	}
	return 0;
}

在while循环中,break用于永久的终止循环

while循环中,continue的用法

例:

int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			//break;//在while循环中,break用于永久的终止循环。
			//在while循环中continue的作用是跳过本次循环continue后边的代码
			continue;
		printf("%d", i);
		i++;
	}
	return 0;
}

在while循环中continue的作用是跳过本次循环continue后边的代码,直接去判断部分,看是否进行下一次循环。

int main()
{
	int ch = getchar();//getchar:获取一个字符
	//printf("%c\n", ch);
	putchar(ch);//putchar:输出一个字符
	return 0;
}
int main()
{
	int ch = 0;
	while ((ch = getchar()) != EOF)
	{
		putchar(ch);
		//ctrl+z 读取到EOF,代码结束
	}
	return 0;

}

应用场景:

int main()
{
	char password[20] = { 0 };
	printf("请输入密码;>");
	scanf("%s", password);//数组的数组名本身就是地址,所以不用再&取地址
	printf("请确认密码(Y/N):>");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败");
	}
	return 0;
}

输入这样的一段代码,运行之后可以发现,并没有确认密码让我们输入的过程,直接就是确认失败,原因是前面输入密码时,scanf只是把2134取走,并没有拿走后面隐藏的\n,从而直接使后面的getchar读取到n,从而确认失败。

所以在这种情况下,我们要清理缓冲区,处理\n,才能让代码正常运行。

int main()
{
	char password[20] = { 0 };
	printf("请输入密码;>");
	scanf("%s", password);//数组的数组名本身就是地址,所以不用再&取地址
	printf("请确认密码(Y/N):>");
	//清理缓冲区
	getchar();//处理\n
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败");
	}
	return 0;
}

引申:

当我们用上述第二个代码,输入12345 abcde时,会发现,又出现了和第一个代码一样的问题。

原因是scanf只拿空格前面的东西,后面abcde\n一个getchar处理不了,所以我们要放多个字符串,一直到\n也读走时再停下。

int main()
{
	char password[20] = { 0 };
	printf("请输入密码;>");
	scanf("%s", password);//数组的数组名本身就是地址,所以不用再&取地址
	printf("请确认密码(Y/N):>");
	//清理缓冲区中的多个内容
	int tmp = 0;
	while ((tmp = getchar()) != '\n')
	{
		;
	}
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值