0

Essentially, the

int main( int argc, char** argv )

does exactly that (or to a very close extent). I was wondering if I could replicate the functionality of the int main( ... ) with other functions as well. For example, say I have a

readline();

function that reads a line from a file. I would like to know how many arguments the line contained argc, as well as an array to each argument that (where a space in the line represents a new argument) argv. So I have two questions:

  1. Does such a function exist in C++ other than the int main() function?
  2. If not, would it be difficult to write one. If the answer to this one is also no, I'd love to hear a few pointers on where to start. I'm not that experienced with C++ and I wasn't sure whether the string class has anything with this functionality.

Thanks!

Amit
  • 7,688
  • 17
  • 53
  • 68
  • 1
    `command "is this one argument"` ? – Karoly Horvath Aug 05 '11 at 11:51
  • 4
    see [How to split a string in C++?](http://stackoverflow.com/questions/236129/), [How do I tokenize a string in C++?](http://stackoverflow.com/questions/53849/), [What parameter parser libraries are there for C++?](http://stackoverflow.com/questions/253556/) – Nick Dandoulakis Aug 05 '11 at 11:55
  • I checked out tokenizing a string and I think the function I'll end up using is `strtok`. I appreciate your help, @Nick. – Amit Aug 05 '11 at 12:13
  • @Amit, `strtok` is simple to use and a bit tricky. For example, it modifies the original string. Choose whatever you feel is appropriate for your problem. – Nick Dandoulakis Aug 05 '11 at 12:28
  • @Amit: We are talking about C++, **not** C. – Jan Hudec Aug 05 '11 at 12:48
  • 3
    `main` does not split anything. In UNIX (where C comes from) the arguments are split (but's it's far from simple split; elaborate quoting rules are used) by the shell, passed as array to operating system and that passes them still as an array to the started program. In Windows, the arguments are passed in single string and the startup emulates the UNIX behaviour, but it still has some quoting rules. – Jan Hudec Aug 05 '11 at 12:56
  • @Jan: Sorry for the confusion. I think I may end up using `boost` after all. – Amit Aug 05 '11 at 15:38

1 Answers1

2

boost::split

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "word1 word2 word3", boost::is_any_of(", "));
cprogrammer
  • 5,503
  • 3
  • 36
  • 56
  • So I assume this will create a vector strs composed of `strs[0] = word1` , `strs[1] = word2`, etc. etc.. If my to-be-split string is `"word1 10 5.0 word2"` and I use this split thing, will I be able to use the integer and floating point number as actual numbers rather than strings? Could I do calculations with them? say... `strs[2] * 10` would result in 100? Because THAT's really what I need :) – Amit Aug 05 '11 at 15:30