Jump to content

Integers via cmd line arguments

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
n00bcoder

n00bcoder

    Newbie

  • Members
  • Pip
  • 8 posts
Hi all,

I was trying to access an integer input via command line [on windows].

Eg:

If I want to reverse an integer where the integer is input via command line, then how do I implement the code for the same?

I tried to use typecasting but that doesn't seem to work :(

here is a bit of the code I could come up with


void main(int argc, char **argv)

{

	int i = 0, j =0, k = 0;

[B]        k = (int) argv[1];[/B] // this is causing the problem.

	printf("%d", k);          // used this statement to check the value returned via typecasting. Always a junk value came up 



	 while( k !=0)

	 {

		i = k % 10;

		j = (j * 10) + i;

		 k = k/10;

		printf("%d", j);

	 }

}


so what is the right way of using integers via command line?

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
The right way involves checking the input character by character, ensuring the user didn't input anything bad, and then if it checks out either converting it manually (I suggest this way) or using strtol to convert it from a string to a long and casting. The fast way, though, is like this:
k = atoi(argv[1]);
atoi though does nothing to check user input so if you get characters it'll just convert to 0, and can easily be given too many numbers, thus overflowing the integer and causing undefined behavior (the worst kind of behavoir), so this function is in no way good at all.

If you're going to take programming seriously though, use the former method, simply take in the string, validate the user input in another function, and convert it manually.
Wow I changed my sig!