• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 423
  • Last Modified:

Integer Command line arguments in C?

Hi,

  This question is about C Programming. How can i convert the arguments accepted from main and convert it to integer?
For example, consider this simple program :

#include<stdio.h>

void main(int argc, int **argv)
{
  int a;
  a=argv[1];
  printf("argv[%d] %s",1,argv[1]);
  printf("\n%d",a);
 
}
(The program compiles and runs fine.)

I have assigned the integer argv[1] to "a" which is the first argument at the command line.

when i look at the results i get a junk character as the output for the second " printf " statement. When i use %s to print the argv[1] it prints the correct number, but if i use %d it prints a junk character. In this case how can i assign an argument accepted as an integer in the command line to an integer variable?
I have tried typecasting it : a=(int)argv[1] does not work, neither does a=(char*)argv[1]; work. where am i doing a mistake?

Please explain how this works.
0
snmurthy
Asked:
snmurthy
1 Solution
 
HermeticCommented:
been a while since I did command line arguments.
I think argv[1] is a pointer to a string.
try a=strtol(argv[1]);
0
 
bcladdCommented:
atoi (ascii to integer) or atol (ascii to long) will work; you want to be careful that there are actually as many command-line parameters as you expect.

-bcl
0
 
MatthewLCommented:
Hi Snmurthy,

Take a look at sscanf as well.  Everything that you can do with scanf from stdin can also be done from within a string.

You can find an example at http://www.cplusplus.com/ref/cstdio/sscanf.html

Matt
0
 
CleanupPingCommented:
snmurthy:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now