当没有输入args时,c++应用程序崩溃

c++ application crashes when no args are entered

本文关键字:c++ 应用程序 崩溃 args 输入      更新时间:2023-10-16

我正在创建一个基于命令行的加密软件。我在这里有一个if语句,用于检查是否没有参数,然后用代码1退出。

if (argc = 0) {
    errorExit("No arguments listed. Type "-h" for help.", 1);
}

errorExit((在我创建的头文件中。

int errorExit(string errMsg, int errorCode) {
cerr << "Error: ";
cerr << errMsg;
cerr << endl;
exit(errorCode);
return NULL;

}

相反,当我不输入参数时,我的程序会崩溃。

Z:CodeC++CodeBlockssimplecryptbinDebug>simplecrypt.exe
terminate called after throwing an instance of 'std::logic_error'
   what():  basic_string::_S_construct null not valid
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Z:CodeC++CodeBlockssimplecryptbinDebug>

为了消除混淆,我将代码块与mingw一起使用,以防它是mingw中的一个bug。

编辑:我意识到我有argc=0而不是argc=0。我意识到了错误,但仍然没有解决问题。

主函数可以这样声明:

int main (int argc, char *argv[]);

当您在命令行中调用程序时,argv[0]将是可执行文件的名称,这意味着如果没有其他参数,则argc应为1。

if(argc == 0){...

在if条件中写入==而不是=