是否可以知道由system(cCmdInput);
开头的命令是否失败,并且显示错误(如果存在)。
cout << endl << "Enter command> ";
getline(cin, cmdInput);
try{
cin.clear();
const char *cCmdInput = cmdInput.c_str();
system(cCmdInput);
}catch (...){
cout << "An error occurred";
}
最佳答案
首先,您不应该使用system()
,因为它存在很大的安全风险(尤其是在使用来自用户的输入(如上面的代码中)时)。而是看一下exec()
系列函数。
但是要回答您的问题,system()
不会引发任何异常。您需要检查返回的内容。 According to the documentation,通常会返回您运行的命令的状态码。您需要查找所用命令的返回码,并对照这些返回码检查system()
返回的值。通常,返回值0表示成功。
例如:
if(system(cCmdInput) != 0)
cout << "Error" << endl;
关于c++ - C++错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306275/