循环小练习——自动关机程序
我们在学习了前面的知识后,可以做一个小的练习,下面是一个自动关机程序的练习。
思路:
- 使用system函数执行关机的系统命令;
- 定义一个数组用来记录用户输入的数据;
- 将用户输入数据与既定数据进行对比,若相同则取消关机,若不同则继续循环。
使用到的知识:
- 关机系统命令: shutdown -s -t time shutdown -a
其中shutdown是关机命令,-s为设置关机、-a为取消关机、-t为倒计时关机、time为倒计时时间
在C语言中,若要使用系统命令,则需由system函数进行调用,其中system使用需要包含<stdlib.h>头文件
#include <stdlib.h>
system("系统命令");
- 两个字符串的比较不能使用 == 来比较,而是需要使用strcmp函数进行比较,其中strcmp函数使用需要包含<string.h>头文件
#include <string.h>
strcmp(字符串1,字符串2);
若相等返回0,若不相等返回1;
具体代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char arr[10] = {0};
system("shutdown - s - t 60");
again:
printf("计算机将在60内自动关机");
printf("输入取消,可取消关机");
if (strcmp(arr, "取消") == 0)
{
system("shutdown -a"); //比较结果相等,取消关机。
}
else
goto again;
return 0;
}
代码结果: