Evan Bloemer
Evan Bloemer

Reputation: 1081

Unix environment running C programs

I am programming C programs in a Unix environment. I need to take a number from a user before the program is executed like so:

./program.out 60

How do I store the integer value in the C program?

Upvotes: 1

Views: 112

Answers (3)

Kabeer Ahmed
Kabeer Ahmed

Reputation: 139

It is quite simple to do and I hope I have got your question right. See below:

#include <stdio.h>

int main(int argc, char* argv[])
{
  printf("Number of arguments is: %d\n", argc);
  printf("The entered value is %s\n", argv[1]);

  return 0;
}

And then compile it on Linux as:

gcc file.c
./a.out 32

The program should print the value you require.

Hope this helps.

Upvotes: 1

sps
sps

Reputation: 2720

int main (int argc, char *argv [ ])
{
   //your code

}

argv [1] will then have the address of the numeric string which contains the number.

Then you can change this to an int if needed.

Upvotes: 1

Paul R
Paul R

Reputation: 213049

You can use argv[] to get command line parameters, e.g.

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

int main(int argc, char *argv[])
{
    int n;

    if (argc != 2)      // check that we have been passed the correct
    {                   // number of parameters
        fprintf(stderr, "Usage: command param\n");
        exit(1);
    }

    n = atoi(argv[1]);  // convert first parameter to int

    // ...              // do whatever you need to with `n`

    return 0;    
}

Upvotes: 7

Related Questions