如何在C程序中运行cmd命令

Joh*_*ara 1 c

我似乎无法弄清楚如何在 C 程序中运行 cmd 程序。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char educode[100];
    printf("Welcome To ACE-IT Edu Software!\n");
    printf("\nPlease Type An Educator Code and then press enter.");
    printf("\nEducator Code: ");
    gets(educode);
    if(educode == 5678){
        system("mkdir test");
    } else {
    printf("\nSorry, thats not a valid Educator Code. To buy an Educator Code, go to https://www.ace-it.edu");
    }


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*hnH 5

由于糟糕的 if 比较(您无法将字符串与整数进行比较),您的系统调用永远不会运行。

错误的:

gets(educode);
if(educode == 5678){
Run Code Online (Sandbox Code Playgroud)

尝试:

gets(educode);
if(strcmp(educode, "5678") == 0 ){
Run Code Online (Sandbox Code Playgroud)

记得也添加#include <string.h>到顶部。

另外,永远不要使用gets()——它已于 2011 年从 C 标准中删除。

fgets()阅读如何使用它后 尝试一下。

  • 我不想用有关修复行终止的信息来重复总是使用“fgets()”的答案。但是,是的,“gets()”存在安全风险,因为用户可以输入任意数量的字符,从而溢出缓冲区(在本例中为“educode”),因此使用“gets()”总是错误的。 (2认同)