1. goto语句格式举例
#include<stdio.h>
int main()
{
again:
printf("hahaha\n");
printf("hehehe\n");
goto again;
return 0;
}
2. goto语句的使用场景
(1)终止程序在某些深度嵌套的结构
- 例如:一次跳出两层或多层循环
for(...)
{
for(...)
{
for(...)
{
if(disaster)
goto error;
}
}
error:
if(disaster)
{
//处理错误情况
}
}
3. goto语句的规则
(1)goto语句无法跨函数跳转
4. 举例
(1)关机程序:
- 代码运行起来后,1分钟内倒计时开始,倒计时完成后关机
- 如果输入“我是猪”,即可解锁倒计时关机程序
“ shutdown -s -t 60 ” ----> 倒计时60s关机,“ -s ” —— 设置关机;“ -t ” —— 设置时间
“ shutdown -a” ----> 取消关机
方法一:
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
int main()
{
char input[10]={0};
system("shutdown -s -t 60"); //将命令通过 system()函数 传给电脑————cmd窗口
again:
printf("电脑将在60s后关机,若想取消关机,请输入:我是猪\n");
scanf("%s",&input);
if(strcmp(input,"NO") == 0)
{
system("shutdown -a");
printf("已成功取消关机!");
}
else
{
goto again;
}
return 0;
}
方法二:
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
int main()
{
char input[10]={0};
system("shutdown -s -t 60");
while(1)
{
printf("电脑将在60s后关机,若想取消关机,请输入:我是猪\n");
scanf("%s",&input);
if(strcmp(input,"我是猪") == 0)
{
system("shutdown -a");
printf("已成功取消关机!");
break;
}
}
return 0;
}