简体   繁体   中英

C++ std::logic_error within for loop using argv

I am new to C++ and I am trying to write a program to take in command line arguments and produce a .desktop file. I am trying to implement identification of the argv values but I keep getting a std::logic_error

My code is:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>

using namespace std;

int main(int argc, char* argv[]) {

    string name;
    string comment;

    for(int i = 1; i <= argc; i++) {
        char* tmp[] = {argv[i]};
        string param = *tmp;
        string paramVal = argv[i+1];
        if(param == "-h") {
            cout << "-h        Display this help dialogue" << endl;
            cout << "-n        Set entry name" << endl;
            cout << "-c        Set entry comment" << endl;
            cout << "-e        Set entry executable path" << endl;
            cout << "-i        Set entry icon" << endl;
            break;
        }
        else if(param == "-n") {
            name = paramVal;
            i++;
            continue;
        }
        else if(param == "-c") {
            comment = paramVal;
            i++;
            continue;
        }
        else if(param == "-e") {

        }
        else if(param == "-i") {

        }
        else {
            cout << "ERROR >>> Unrecognised parameter %s" << param << endl;
        }
    }

    cout << "Name: %s\nComment: %s" << name << comment << endl;
    return(0);
}

The program compiles fine (using g++) but when I try to run ./createDesktopIcon -na -cb I get the following error

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

Please help as it is very frustrating

Here are the problems I see:

i <= argc

You want to compare i < argc because the argv[argc] element in the array is actually one past the last element in the argv array.

Also, here:

string paramVal = argv[i+1];

This will access the array out of bounds as well.

You might want to look at getopt to do all of this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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