How to read in numbers as command arguments? How to read in numbers as command arguments? c c

How to read in numbers as command arguments?


Assuming the C language:

  • Command line arguments are found in the argv array - argv[1], argv[2] etc.
  • Converting a string argument to an integer can be done with the atoi function.
  • Output can be done with the printf function.

[Trying to teach you to fish, rather than providing a fish. Good luck!]


Assuming that you are using bash, you can use $1, $2, etc for those arguments. If, however, you are useing C, you're code should looks something more like this:

#include <stdio.h>#include <stdlib.h>main(int argc, char *argv[]) {    if(argc<=1) {        printf("You did not feed me arguments, I will die now :( ...");        exit(1);     }  //otherwise continue on our merry way....     int arg1 = atoi(argv[1]);  //argv[0] is the program name                                //atoi = ascii to int     //Lets get a-crackin! }

Hope this helps.


Firstly, if you run your C program as

./a x y

then a is argv[0], x is argv[1], and y is argv[2], since C arrays are 0 based (i.e. the first item in the array is indexed with 0.

Realize that argv is an array (or I've always thought of it as an ARGument Vector, though you might think of it as an array of ARGument Values) of character string pointers. So, you need to convert the strings to integers. Fortunately, C has library functions to convert ASCII to integer. Look at the stdlib.h documentation.

Good luck!