首页 > 解决方案 > 我的 C 程序因未知原因而崩溃

问题描述

所以我的程序本来是一个小命令行,但它一直在崩溃:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>    

void main()
{    
    char cmd;
    for(;;)
    {
        fgets(cmd,255,stdin);
        if (strstr(cmd,"CD")!=NULL )
        {
            cmd +=2;
            SetCurrentDirectory(cmd);
        }
        else
        {
            system(cmd);
        }
    }
}

编译器输出是预期的左值。

标签: c

解决方案


也许你正在寻找做这样的事情:

void main()
{    
    char cmd[255]; // this allocate a character array to store the command in
    for(;;)
    {
        fgets(cmd,255,stdin); // get the characters from stdin and store them in the cmd character array with a max length of 255
        if ( strncmp(cmd, "CD ", 3) == 0 ) // check if the first three characters are "CD "
        {
            SetCurrentDirectory(&cmd[3]); // pass the string not including the first 3 charcters, which should be "CD "
        }
        else
        {
            system(cmd);
        }
    }
}

推荐阅读