Re: Create a list of numbers

From: Victor Bazarov (
Date: 10/27/04

Date: Wed, 27 Oct 2004 10:38:10 -0400

Eric Lilja wrote:
> Hello, I'm working on my C++ homework and I have a question about the
> following function.
> It's part of my code the handles command line arguments. Here's the code:
> static void
> extract_numbers(const char* optarg, vector<string>& numbers)
> {
> const char* str = optarg;
> while(true)
> {
> string s(str);
> string::size_type index = s.find_first_of(',');
> if(index == string::npos)
> {
> string temp(s.c_str(), s.length());
> numbers.push_back(temp);
> break;
> }
> else
> {
> string temp(s.c_str(), index);
> numbers.push_back(temp);
> str += (index + 1);
> }
> }
> }
> optarg points to a null-terminated string of the following form:
> somenumber1,somenumber2,somenumber3
> where somenumber* is a, *drumroll*, number. It needs to extract these
> numbers and put them in the vector. Note that
> optarg may point to anything, I haven't made any sanity checks on the input
> at this point and it may also
> contain only one number. My way seems to work for "friendly" input, is it ok
> to hand in as it is (I need to perform better on
> this assignment) or can it be improved/bug fixed?

Try it with different inputs, like


If you get it all there, you're fine.

Since it's only part of the program, you are still in need to fix the
conversion later and detect any errors during that. It would be nice
if your program while detecting the error in the input knew where the
erroneous input is in the original string. If you have spare time, you
could work on that.


Relevant Pages

  • TIP #185: Null Handling
    ... nulls, and command modifications for manipulating them. ... Tcl deals with strings, the universal medium for representing data. ... is know and it is an empty string, but if a respondent forgets to give ...
  • Re: Determine how Word was launched
    ... inspect the command line used to launch Word. ... Private Declare Function GetCommandLineA Lib "kernel32" As Long ... Public Function GetCommandLineAs String ... Dim lngCmdLinePtr As Long ...
  • Re: Class.getMethod in classs static initializer block
    ... I just wanted to add that I had some similar code for a "command line server" project. ... static private final boolean DEBUG = true; ... {public ReturnCode runCommand(String s) ... public ReturnCode parseLine(String line) ...
  • Re: New "base document" available
    ... How to go about retrieving command line parameters? ... the command line arguments (and environment variables) ... Keyword and positional parameters can be mixed in the same command line. ... clp-name points to a string containing "P1" ...
  • A plan for handling command line options
    ... Getopt is meant to be used by calling it once for each command ... In each case the first argument is an option string and the ... provide an error handling interface that the user can access. ...