1

[My program needs to accept input from the linux command line and organize it into arrays. a[0] is supposed to show the first integer input by the user. However I get a[0] = ./a.out. How would I remove ./a.out and have a[0] = the first integer?]

 #include <iostream>
 #include <string>
 #include <cmath>
 #include <stdlib.h>
 using namespace std;

 int main ( int argc, char *argv[] )
 {    
         for(int i = 0; i < argc;++i)
         {

                 printf("\nargv[%d]: %s\n",i,argv[i]);
         }
 }
mrflash818
  • 930
  • 13
  • 24
LostHobbit
  • 11
  • 4

2 Answers2

3

Start at index 1, but display as if it were index 0.

for(int i = 1; i < argc;++i)
{
    printf("\nargv[%d]: %s\n", i-1, argv[i]);
}
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • Thank you, I knew I needed to minus by one but I was a little confused on where. I really appreciate your help! – LostHobbit Jan 29 '20 at 20:52
0

You can initialize an std::vector<std::string> containing the command line arguments from argv by simply skipping the first element (i.e., the program name):

#include <vector>
#include <string>
#include <iostream>

auto main(int argc, char *argv[]) -> int {
   // skip the program name by starting at offset 1 instead of 0
   std::vector<std::string> args(argv + 1, argv + argc);

   for (auto const& arg: args)
      std::cout << arg << '\n';
}

This way, args[0] will correspond to the first argument that was provided to the program at the command line. Assuming the program is called a.out, running it as:

./a.out 1 2 3

results in the output:

1
2
3

The program name, i.e., ./a.out, was skipped when creating the args vector, so it only contains the arguments passed at the command line, i.e., 1, 2 and 3.

JFMR
  • 23,265
  • 4
  • 52
  • 76