Home > Net >  C perform action when command line argument is empty [duplicate]
C perform action when command line argument is empty [duplicate]

Time:09-17

I've been working on a program recently, and got a bit stuck on a step. When the program is run from the shell, it performs an action when there are no parameters passed. Perhaps someone could assist me, or point me in a proper direction?

int main(int argc, char* argv[])
{
    string paramPassed = argv[1];
    if(paramPassed == "")
        cout << UseDriver();
    
    else if(paramPassed == memMap)
        cout << UseMemMap();
    
    else{
        if(paramPassed == help)
            cout << PrintProgramHelp();
        
        else if(paramPassed == helpMin)
            cout << PrintProgramHelp();
        
        else
            cout << "Wrong selection. Input --help or -h for more options." << endl;
    }
    cout << "Press any key to continue." << endl;   
    cin.get();
    return (0);
}

Above code on no input gives me:

terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_construct null not valid

What can I do? If I don't provide any parameter on program start, it gives me a segmentation fault.

Is there something I'm missing here?

CodePudding user response:

If there are no command line arguments, then indexing at argv[1] is undefined behavior. There is simply nothing at that index, as opposed to an empty string which is what you're checking.

To check that there are no command line arguments (after the program name, which is always argv[0]), you can simply use the value of argc like this

if (argc == 1)
  // do whatever when no command line args are provided
  • Related