I wrote a program for exercise 1-20 from the book the c programming language.
The program is:
#include <stdio.h>
#include <stdlib.h> /* for atoi() */
main(int argc, char *argv[]) {
int c,i,n;
if (argv[1])
n=atoi(argv[1]);
while((c=getchar())!=EOF) {
if(c!='\t') {
printf("%c",c);
}else
{
for(i=1;i<=n;i++) {
printf(" ");
}
}
}
}
How can i pass arguments to main() function in c language without the atoi() function?
All arguments to a program is passed as strings, with argc
telling you how many there are and argv
containing the actual arguments.
If you need a numerical value you have to somehow convert them, and you can use atoi as you have done, or use one of the many libraries to parse options, like getopt
You should check argc
instead of checking argv[1]
, so
if (argc >= 2)
n=atoi(argv[1]);
Have a look at this handy guide.