要想设计这个程序,就要了解两个必不可少掉的指令:system("shutdown -s -t 60), system(shutdown -a), system是执行系统命令的一个函数,shutdown -s是关机指令,shutdown -a 是取消关机,-t 60是60秒后关机,system函数要用到Windows.h库文件。
思路:检查用户输入的字符串与已设定的字符串是否相同(strcmp),如果相同就取消关机,不相同就继续重新输入,直到关机。
代码如下:
#include <stdio.h>
#include<Windows.h>
#include<string.h>
int main()
{
char input[20] = { 0 };
system("shutdown -s -t 60");//shutdown -s是关机指令,-t 60是60s后关机,需用到Windows.h头文件
again:
printf("请注意,电脑将在一分钟后关机,如果输入:我是猪,就取消关机\n请输入:");
scanf("%s", input);
if (strcmp(input, "我是猪") == 0)//strcmp用于比较字符串,用到string.h
system("shutdown -a");//这是取消关机指令
else
goto again;
return 0;
}
while循环语句也可以用:
#include <stdio.h>
#include<Windows.h>
#include<string.h>
int main()
{
char input[20] = { 0 };
system("shutdown -s -t 60");
while (1)
{
printf("请注意,电脑将在一分钟后关机,如果输入:我是猪,就取消关机\n请输入:");
scanf("%s", input);
if (strcmp(input, "我是猪") == 0)
{
system("shutdown -a");
break;
}
}
return 0;
}