简体   繁体   中英

Adding even / odd elements in *argv[] to arrays

I'm fairly new to C++ and I'm making a simple program which takes values and units as system arguments and converts them all to a single unit. The command line execution and input goes something like this:

./unit_conv 3 feet 5 inches centimeters

The values and units are separated by spaces, and the final argument is the unit I want to convert everything to.

My approach to get input is to add all even elements of *argv[] before the last element to an integer array called 'values', and add all odd ones to a character pointer array called 'units'. Below is my attempted implementation:

if (argc % 2 == 0) {
  char * desiredUnit  = argv[argc - 1];
  int values[argc];
  char * units[argc];

  int j;
  int k;
  for (int i = 1; i < argc; i++) {
    if (i % 2 == 1) {
      values[j] = atoi(argv[i]);
      j++;
    }
    else {
      units[k] = argv[i];
      k++
    }
  }
}

Upon the execution I mentioned above, I get the following:

Segmentation fault (core dumped)

I know the seg fault is occurring within my for loop. I don't see how the program is attempting to access restricted memory, though. I've been stuck with this one for quite awhile.

Hopefully I provided enough info, but if my question is too vague please let me know.

Thanks!

Have you tried using STL?

std::vector<std::string> units{};
std::vector<int> values{};

for (std::size_t i {1}; i < argc; ++i) {
    if (i % 2 == 0) {
        units.push_back(std::string{argv[i]});
    } else {
        values.push_back(std::atoi(argv[i]));
    }
}

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