我一直在尝试使用 C++ 命令行参数,但遇到了一些问题。最初我试图使用“==”运算符将“argv”与字符串进行比较。我很快了解到比较的是指针而不是值。我修复了那个错误,但现在我在运行时遇到了这个错误。
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted (core dumped)
程序编译正常,我也没有收到编译器的警告。这是我的源代码,以便您帮助我找到问题。
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
//Deal with arguments and send them to the correct functions
if (argc >= 2){
string op = argv[2];
if (op == "-a" || op == "--automatic"){
cout << "Test";
}
return 0;
}
//Or, just write help and info
cout << "\n";
cout << "bwc v0.0.1U-(Unstable)\n\n";
cout << "Usage: bwc <operation> [...]\n";
cout << "Operations:\n";
cout << " bwc {-a --automatic} <file(s)>\n";
cout << " bwc {-i --interactive}\n";
cout << " bwc {-c --error-codes}\n";
cout << "\n";
return 0;
}
最佳答案
您对 argv[]
的索引差了一个。变化:
string op = argv[2];
到:
string op = argv[1];
关于c++ - 尝试获取命令行参数的核心转储。 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233082/