简体   繁体   English

尝试使用命令行参数的核心转储。 (C ++)

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

I have been experimenting with C++ command line arguments and have run into a few problems. 我一直在尝试使用C ++命令行参数,但遇到了一些问题。 Originally I was trying to compare "argv" with a string using the "==" operator. 最初,我试图使用“ ==”运算符将“ argv”与字符串进行比较。 I quickly learned that that compares the pointers not the values. 我很快了解到,这是比较指针而不是值。 I fixed that error but now i am getting this one at run time. 我修复了该错误,但现在在运行时得到了该错误。

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid
Aborted (core dumped)

The program compiles fine, and I'm not getting warnings from the compiler either. 该程序编译良好,我也没有从编译器收到警告。 Here is my source code so that you can help me find the problem. 这是我的源代码,以便您可以帮助我找到问题。

#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;
}

Your indexing of argv[] is off by one. 您对argv[]索引减少了一个。 Change: 更改:

string op = argv[2];

to: 至:

string op = argv[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM