0

I am not familiar with using command line arguments. I am trying to take a vector input as a command line argument. Please refer the below code and help me with the error.

#include<bits/stdc++.h>
#include<vector>

using namespace std;

int main(int argc, char *argv[]){
    vector<int> arr;
    cout<<"Arguments are:\n";
    for(int i = 1 ; i < argc ; i++){
        arr.push_back(argv[i]);
    }
    for(int i = 0 ; i < arr.size() ; i++){
        cout<<arr[i]<<" ";
    }
}

The code is giving below error.

enter image description here

  • 3
    You want to have `vector arr;` there, not `vector arr;`. Also stop doing [`#include`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) please. – πάντα ῥεῖ Jan 01 '21 at 14:23
  • 2
    or a function (as [`std::stoi`](https://en.cppreference.com/w/cpp/string/basic_string/stol)) to convert the `char*` into `int`. – Jarod42 Jan 01 '21 at 14:26
  • 1
    Post error message as text first. (additional image/link might be fine). – Jarod42 Jan 01 '21 at 14:29
  • You can use the vector constructor: `vector arr(argv + 1, argv + argc);` instead of the loop – Thomas Sablik Jan 01 '21 at 14:30

1 Answers1

0

The problem is, that your vector contains ints, but the command line arguments are strings (see error). You should convert the argv[i] to int, than use the push_back(). You can use stoi() which converts string to int, but keep in mind that it could happen when not just digits appear in the command line argument.

Enlico
  • 23,259
  • 6
  • 48
  • 102
Geri Papp
  • 28
  • 8