System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

Passing an integer argument to a C program on command line

SOLVED
Go to solution
tony j. podrasky
Valued Contributor

Passing an integer argument to a C program on command line

Hello folks;

A bit off-topic but I *am* using GCC on a Linux box. :-)

I have written a program, that at startup, I would like to enter an integer on the command line and pass it to the program.

All I can find is the ARGV and that only appears to pass an array of pointers.

int main(int argc, char *argc[])

Any ideas?

(Oh - I came up with a work-around which is taking the pointer and doing a STRCMP with a known value and if there is a match setting the variable to the integer I would have put on the command line. I just can't believe that with all the flexibility of C that there isn't a better way. I *DID* look thru a lot of my C programming books but could not any reference).

regards,
tonyp (aka hunybuny)
REMEMBER: Once you eliminate your #1 problem, #2 gets a promotion.
4 REPLIES
Steven Schweda
Honored Contributor
Solution

Re: Passing an integer argument to a C program on command line

> [..] I *am* using GCC on a Linux box. [...]

I'm not, but:

alp $ type nil.c
#include
#include

main( int argc, char **argv)
{
long val;

if (argc > 1)
{
val = strtol( argv[ 1], NULL, 10);
printf( " val = %ld.\n", val);
}
}

alp $ cc nil
alp $ link nil

alp $ exec nil

alp $ exec nil 29 30 31
val = 29.

alp $ cc /version
HP C V7.3-009 on OpenVMS Alpha V7.3-2


Seems to work with a GCC somewhere, too:

sol# gcc -o nil nil.c
sol# ./nil
sol# ./nil 19 20 21
val = 19.

sol# uname -a
SunOS sol 5.10 Generic_137137-09 sun4u sparc sun4u
sol# gcc --version
gcc (GCC) 3.4.6
[...]


The program gets a string, but, given a
string, many things are possible.
Matti_Kurkela
Honored Contributor

Re: Passing an integer argument to a C program on command line

There are many ways to convert a string to an integer. Steven already mentioned strtol(), but there is also atoi(). If your command line argument may contain "an integer and something else" (e.g. something like "10k"), you can use sscanf().

See also getopt(): it is a bit complicated but makes it easy to parse a large number of options in any order.

MK
MK
tony j. podrasky
Valued Contributor

Re: Passing an integer argument to a C program on command line

Dear Steven and Matti;

Thank you for the help.

The suggestion works perfectly!

regards,
tonyp (aka hunybuny)
REMEMBER: Once you eliminate your #1 problem, #2 gets a promotion.
tony j. podrasky
Valued Contributor

Re: Passing an integer argument to a C program on command line

Members provided the solution.

Problem Resolved.

regards,
tonyp (aka hunybuny)
REMEMBER: Once you eliminate your #1 problem, #2 gets a promotion.