两种方式(goto语句以及while循环)实现C语言关机小程序

用C语言写的关机小程序简单易懂,可以拿去整蛊室友同学(每天一个挨打小技巧),下面我就给出两种方式实现这个代码,欢迎大家讨论补充。

1.用goto语句实现:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	char arr[30] = { 0 }; 
	system("shutdown -s -t 60");
again:
	printf("请输入:我是猪,来取消关机\n");
	scanf("%s", arr);
	if (0 == strcmp(arr, "我是猪"))
	{
		system("shutdown -a");
	}
	else
	{
		goto again;
	}
	return 0;
}

 2.用while循环实现:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	char arr[20] = { 0 };
	system("shutdown -s -t 60");
	printf("输入 我是猪 制止关机\n");
	
	while (1)
	{
		scanf("%s", arr);
		if (0 == strcmp(arr, "我是猪"))
		{
			system("shutdown -a");
			break;
		}
		else if (0 != strcmp(arr, "我是猪"))
		{
			printf("请重新输入:\n");
		}
		
	}

 这里需要注意输入scanf要放在while循环内部,不然输入错误指令的话会导致程序无限循环出错。

补充说明:关机指令: system("shutdown -s -t 60")  , shytdown是windows系统cmd关机指令, -s进行设置, -t 60 进行倒计时设置,60s的意思。  system("shutdowm -a")取消关机指令 。

比较两个字符串是否相等需要用 strcmp(....,....)函数,相等的话返回值为0; 不可以用 == 进行比较,这里容易出错,需要特别注意。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值