C++系统功能"not reconized as internal or external command"

C++ System function "not reconized as internal or external command"

本文关键字:or external internal command reconized 系统功能 not C++ as      更新时间:2023-10-16

代码如下:

#include <iostream>
#include <string>
using namespace std;
int main(){
    cout << "type dir" << endl;
    string command;
    cin >> command;  //typed C:Java
    const char* cml = ("cd C:" + command).c_str();
    system(cml);
    cout << "[System]: Set!";
}

,结果如下:

'exe' is not recognized as an internal or external command,
operable program or batch file.

如果我只是键入system("cd C:Java");,那么它就工作了。但是如果我像上面那样将const char传递到系统函数中,我会得到一个错误,即无法识别exe。

这是未定义的行为:

const char* cml = ("cd C:" + command).c_str();

变量cml正在被初始化,其C-string指针来自std::string,作为连接的结果返回。然而,这个结果是一个临时变量,在语句结束后被丢弃。因此,cml指向的字符数组指针在这行之后已经被释放了。

下面的语句将保留连接结果,以便在接下来的语句中使用:

string cml = "cd C:" + command
system(cml.c_str())