我有这个C代码:
#include <stdio.h> #include <stdlib.h> int main() { int a; printf("Please enter a number:\n"); scanf("%d",&a); printf("Your number is: %d\n",a); system("echo %d",a); }
我感兴趣的是最后一条命令, system()
函数以及为什么我不能打印我的variables,就像我用printf()
打印的那样。 我希望能够询问用户一些input,让我们说一个string,然后将其传递给系统function。
实际例子:
询问用户的文件夹名称
system("mkdir %s", FolderName);
先谢谢你! 🙂
使用snprintf
#include <stdio.h> #include <stdlib.h> int main() { int a; char buf[BUFSIZ]; printf("Please enter a number:\n"); scanf("%d",&a); printf("Your number is: %d\n",a); snprintf(buf, sizeof(buf), "echo %d",a); system(buf); }
system
,不像printf
不接受多个参数,它只接受一个参数,一个const char *command
。 所以你需要先在内存中建立完整的命令字符串然后传给系统。
一个例子是:
char buf[32]; sprintf(buf, "echo %d", a); system(buf);
你需要注意不要把更多的字符写入buf比buf有空间。 您可能需要阅读snprintf
的手册页,以更安全的方式重写代码。
另外:如果你的代码真的编译,那么请编译一个更高的警告级别。 至少这会给你警告你正在用比你应该更多的参数调用系统。
系统函数没有像printf这样的格式化选项,而是系统函数将C字符串作为参数。
看看下面的网站了解更多信息。
http://www.tutorialspoint.com/c_standard_library/c_function_system.htm