Home > Net >  How to utilize command line values in a loop
How to utilize command line values in a loop

Time:03-03

My code is suppose to get the factorial of a passed value. I spoke with my professor and he told me to use int argc, char* aragv[] arguments. It complies but will loop once and will only return the initial value.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
   int fact = 1;
   if(argc>1)
   { 
        printf("Too many inputs!\n");
        return -1;
   }
   int n = atoi(argv[1]);
   for(int i = 1; i <= n;i  )
   {
       fact *= i; 
   }
   printf("%d\n", fact);
   return 0;
}

CodePudding user response:

Explain..

In the C language, main argv[0] always contains the program filename, argv[1] is your first commandline parameter.

argc is like an array count from 0, so

If you have argc=1, you have no commandline parameters.

If you have argc=2, you have one commandline parameter.

Check out https://www.tutorialspoint.com/cprogramming/c_command_line_arguments.htm

CodePudding user response:

Heres how to read the command line to get one integer

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
   if(argc != 2){
       printf("wrong arguments\n");
        return -1;
    }
    
   int n = atoi(argv[1]);
   printf("you entered %d\n", n);
   return 0;
}

note that this does not deal with the case where there is 'frog' instead of '42' on the command line. I leave that up to you to work out

  • Related