尝试获取命令行参数的核心转储.(C++)

Core Dump with trying to take command line arguments. (C++)

本文关键字:转储 C++ 核心 取命令行 参数      更新时间:2023-10-16

我一直在尝试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)nn";
    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];