循环语句的学习
一、switch循环语句的学习
switch允许嵌套。如果没有break语句切断,则连续执行case
#include <stdio.h>
#include <string.h>
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:
m++; //此时m=3 ,n不变
case 2:
n++; //此时 n=2
case 3:
switch (n) //当前n=2
{//switch允许嵌套使用
case 1: //因此case 1不执行。
n++;
case 2: //从此开始执行。
m++; // 此时m=4
n++; //此时n=3
break; //结束当前switch语句
default:
break;
}
case 4:m++; //此时m=5
break;
default:
break;
}
printf("m=%d,n=%d\n",m,n);
return 0;
}
二、使用getchar() 接收字符
getchar()可以接收字符,同样 putchar(ch) 可以输出字符串
//ctrl+z = EOF 则跳出循环
// EOF== end of file,本身的值是-1;
#include <stdio.h>
int main()
{
int ch = 0;
//ctrl+z = EOF 则跳出循环
// EOF== end of file,本身的值是-1;
while ((ch=getchar()) != EOF)
{
putchar(ch);
}
//int ch = getchar(); //输入字符串
//putchar(ch) 输出字符串
return 0;
}
二、continue跳过当前循环
#include <stdio.h>
int main()
{
int i =0;
while (i<=10)
{
i++;
if(i==5)
continue; //continue是跳过当前循环。
//break;
printf("%d\n",i);
}
return 0;
}
三、getchar()的特殊用法
用getchar()清空缓冲区
#include <stdio.h>
int main()
{
int ret = 0;
char password[20] = {0};
printf("请输入密码:>");
scanf("%s",password);
//缓冲区还剩下'\n'
getchar(); //采用getchar()清空缓冲区
printf("请确认(Y/N):>");
ret = getchar(); //Y/N
if(ret == 'Y')
{
printf("确认成功\n");
}
else
{
printf("放弃确认\n");
}
return 0;
}
四、for 循环。
for三个语句,初始化,判断,调整。
#include <stdio.h>
int main()
{
int i =0;
// for三个语句,初始化,判断,调整。
for ( i = 0; i <=10; i++)
{
printf("%d ",i);
}
return 0;
}
总结
通过记录每天的学习内容,不断的提升。
第七天打卡(如何快速的学习C/C++语言)