Question

I have been experimenting with C++ command line arguments and have run into a few problems. Originally I was trying to compare "argv" with a string using the "==" operator. 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;
}
Was it helpful?

Solution

Your indexing of argv[] is off by one. Change:

string op = argv[2];

to:

string op = argv[1];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top