user1692517
user1692517

Reputation: 1152

How to run a parameter while executing a C file?

I have a working program that computes the cube of a number in a compute_cube.c file. It compiles into compute_cube.

Now I would like to run it through the terminal like this:

./compute_cube 3

And then the terminal would show my program's result (27).

How would I go about doing this? What should I be reading up on?

Upvotes: 2

Views: 56

Answers (2)

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

Use C language's argc and argv:

int main(int argc, char **argv)
{
    if (argc > 1)
        printf("%s", argv[1]);
}

Upvotes: 2

Kristian Oye
Kristian Oye

Reputation: 1202

I know its already been answered but... argc of course = 0-based number of command line args including program name at index 0 and argv contains actual command line text.

#include <stdio.h>

int main(int argc, char **argv) {
  if (argc > 1) {
    int n = atoi(argv[1]);
    printf ("%d^3 = %d\n", n, n*n*n);
    return 0;
  }
  else printf("Usage: %s <num>\n", argv[0]);
  return 1;
}

Upvotes: 1

Related Questions