我一直在学习c,我想创建一个c程序,它应该做的就是在某个用户输入时间后关闭计算机。
我知道如何立即关闭,使用以下代码:
#include<stdlib.h>
int main()
{
system("C:\\WINDOWS\\System32\\shutdown /s /t 00");
return 0;
}
我创建.exe文件,并执行,它运行正常。但我不知道如何在用户输入一段时间后关机。我尝试了#运算符:
#include<stdio.h>
#include<stdlib.h>
#define shutown(x) system("C:\\WINDOWS\\System32\\shutdown /s /t" #x);
int main()
{
int t;
printf("\n enter secs :");
scanf("%d",t);
shutdown(t);
}
但程序没有用。 我从来没有真正使用过#manrator,但是搜索过它,在这里:
https://msdn.microsoft.com/en-us/library/7e3a913x.aspx
但是,我仍然不确定我是否正确使用了操作员。
我还想创建一个程序,它会在用户输入名称的Windows中创建一个文件夹,但我打算使用#manrator,我想我正在做 出了点问题。
请告诉我我哪里出错了,以及执行相同任务的任何其他逻辑。
非常感谢!
答案 0 :(得分:4)
#
运算符是一个预处理程序运算符,这意味着它都是在编译时完成的。您无法使用用户的值。你实际上最终得到了:
system("C:\\WINDOWS\\System32\\shutdown /s /t" "t");
这绝对不是你想要的。
您实际上希望有一个本地字符串缓冲区,您将使用sprintf
之类的内容打印该值,然后调用system(buffer);
这将做你想要的:
int main()
{
int t;
char buffer[100];
printf("\n enter secs :");
scanf("%d",&t); // Note that you need &t here
sprintf(buffer, "C:\\WINDOWS\\System32\\shutdown /s /t %d", t);
system(buffer);
}
答案 1 :(得分:0)
在#define
声明中,shutdown
拼写为shutown
(复制+粘贴错误?)。
要在#define
宏中使用变量,只需输入变量的名称即可。例如:
#define shutdown(x) system("C:\\WINDOWS\\System32\\shutdown /s /t" x);
但是调用宏中的任何函数就像在其他地方调用它们一样。它不会将x
替换为t
的值,而是将其替换为文字t
。因此,
system("C:\\WINDOWS\\System32\\shutdown /s /t" t);
不起作用。您需要将这两个字符串连接起来strcat
。
您需要#include <string.h>
才能使用strcat
,但在您完成此操作后,我们需要修改shutdown
:
#define shutdown(x) system(strcat("C:\\WINDOWS\\System32\\shutdown /s /t ", x));
免责声明:我没有测试过这些代码,它只是一般指南。可能存在问题,但这是有用的要点。将其视为伪代码。