Ubuntu-Chicago Parsing argv in C++

Max Luebbe max.luebbe at gmail.com
Mon Sep 11 04:26:00 BST 2006


Ok.
You've got several problems.

First off - indexing in C/C++/Java starts at zero.
The first character in a string or item in an array is 0.
Your else if should be:
else if (*argv[i] == 'g') <=== note i'm using single quotes to check a
character type

using pointer arithmetic to illustrate a point,
you could also check that (*(argv[i]+1) == 'r'

Next, you cannot compare strings like that.
Look at your definition.
char *[] is an array of pointers to chars.
A pointer is a index in memory, and will never ever equal a string
constant.

You need to use a string comparison function like strcmp()
(string.h)

Try compiling with warnings on 

gcc -wall sandbox.c

this will yell at you for bad style, and even though a program may still
compile without error doesnt mean it wont blow up later.

check out:
#include <unistd.h>
and the function getopt()
hope this helps

Ask more questions if you've got em.
-Max




On Sun, 2006-09-10 at 21:39 -0400, Eric O'Neal wrote:
> Heya, I was hoping you guys could help me with some novice programming
> woes.  I'm trying to parse command-line options (I want to write the
> parser myself for the experience), and somehow am stuck up on...
> well... I dunno, but it's not working. 
> 
> The logic in my code is comparable to the following sample:
> 
> ---------------------------
> 
> #include <iostream>
> 
> using namespace std;
> 
> int main( int argc, char *argv[] )
> {
>     for (int i = 1; i < argc; i++) 
>     {
>         cout << "*Debug: Parsing(" << argv[i] << ")" << endl;
>         if (argv[i] == "greetings")
>         {
>             cout << "Found: greetings" << endl; 
>         }
>         else if (argv[i] == "g")
>         {
>             cout << "Found: g" << endl;
>         }
>         else
>         {
>             cout << "Invalid" << endl; 
>         }
>     }
>     return 0;
> }
> 
> ---------------------------
> 
> The above compiles fine with GCC v4.0.1 into a binary named "sandbox".
> But when I run it:
> 
> --------------------------- 
> 
> $ ./sandbox greetings
> *Debug: Parsing(greetings)
> Invalid
> *Debug: Parsing(g)
> Invalid
> 
> ---------------------------
> 
> I though I had something working earlier, but whatever I changed broke
> it.  Help? 
> 
> SigmaX
> 
> -- 
> My home page:  http://www.SigmaX.org
> 
> "ttocs laeno cire oshkosh b'gosh fyedernoggersnodden nicht stein bon
> probiscus"
> 
> "Education is what remains after one has forgotten everything he
> learned in school" 
>               -- Albert Einstein




More information about the Ubuntu-us-chicago mailing list