c语言用命令语句让电脑关机

电脑如何用程序关机,在程序中打开命令提示符,输入关机命令语句,shutdown -s -t 60,电脑就会在60秒之后关机,继续输入shutdown -a,电脑会取消关机,这是直接对电脑发出命令。在c语言中也可以用代码让电脑关机,当代码运行之后,电脑就会关机,按提示输入相应的内容,就会取消关机。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	char input[20] = {0};
	system("shutdown -s -t 60");
again:
    printf("电脑将在一分钟内关机,如果输入:我是猪,就取消关机\n");
	scanf("%s", &input);
	if (0 == strcmp(input,"我是猪"))
	{
		system("shutdown -a");
	}
	else
	{
		goto again;       //goto语句,如果输入内容不是"我是猪",程序跳转到again,继续提示用户输入"我是猪"
	}
	return 0;
}
代码中的goto语句也可以换成while,把关机和取消关机的命令放到while的循环体内,输入“我是猪”,break跳出循环。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	char input[20] = {0};
	system("shutdown -s -t 60");
	while (1)
	{ 
		printf("电脑将在一分钟内关机,如果输入:我是猪,就取消关机\n");
	    scanf("%s", &input);
	     if (0 == strcmp(input,"我是猪"))
	    {
		       system("shutdown -a");
			   break;
	    }
	}
   return 0;
}	


猜你喜欢

转载自blog.csdn.net/ch15029286692/article/details/80103226