0

I’m creating a function void foo(int argc, char** argv) in the same style as main from the command line. using a input from std::cin.

ive experimented with a couple of ideas mainly using strtok and vectors, as well as a method involving reading directly from the input stream and reallocating a array. but can’t quite figure out the best method to achieve this without a vast amount of array reallocation or using vectors that seemed to have unnecessary overheads.

void foo(int argc, char** argv) {
   //do somthing.
   return;
}

int main() {
   std::string tmp;
   std::getline(std::cin, tmp)

   //code here.

   foo(var_count, vars);
}

many thanks.

edit: looking furthur into this the c style strtok feature is depreceated and has been replaced with new varients that appear to have platform compatability issues.

  • can you explain _why_? The `main` command line input interface is that way for legacy reasons. Modern C++ has much better ways to pass information around. – JHBonarius Feb 20 '21 at 21:03
  • Don't know about OP, but I once had to build a [QApplication](https://doc.qt.io/qt-5/qapplication.html) with arguments not necessarily forwarded from main. I agree it should be avoided if possible though. – m88 Feb 20 '21 at 21:06

2 Answers2

0

You've hit a bit of an issue here. You're not sure what the string size is, but you need an array of characters. If I were you, I'd stick with strtok() and maybe something like a std::list where you can resize it at any time and access at a (relatively) fast rate.

Example...

std::list<char*> delim_list;
char_evaluate = strtok (tmp," ");
while (char_evaluate != NULL)
{
  list.push_back(char_evaluate);
  char_evaluate = strtok (NULL, " ");
}

Haven't thrown this into a compiler, so let me know if it has issues.

TheN00bBuilder
  • 94
  • 1
  • 11
0

The problem with main-like functions is that string literals are const and you need a contiguous sequence of mutable char* pointers. AND you need to be sure whatever those char* point to won't be freed before the end of foo().

Argument-string-splitting aside, this should work:

std::vector<std::string> args = {"hello", "world"};
std::vector<char*> c_args;
for (auto& arg: args) c_args.push_back(&arg[0]);
foo(static_cast<int>(c_args.size()), c_args.data());
m88
  • 1,968
  • 6
  • 14