Unix环境下运行C程序

Eva*_*mer 1 c unix

我正在Unix环境中编写C程序.我需要在程序执行之前从用户那里获取一个数字,如下所示:

./program.out 60

如何将整数值存储在C程序中?

Pau*_*l R 7

您可以使用argv[]获取命令行参数,例如

#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;    
}
Run Code Online (Sandbox Code Playgroud)