2015-04-21 111 views
1

我在Unix环境下编程C程序。我需要的是像这样执行程序之前从用户采取一些:运行C程序的Unix环境

./program.out 60

我怎么整数值存储在C程序?

+3

使用'argv',阅读有关命令行参数。 –

+0

谢谢你指点我正确的方向(双关语意)。我明白我现在需要做什么。 –

+0

阅读http://www.cprogramming.com/tutorial/c/lesson14.html有关C程序的命令行参数。 –

回答

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;  
} 
1
int main (int argc, char *argv [ ]) 
{ 
    //your code 

} 

argv [1]届时将有包含数量的数字字符串的地址。

然后,如果需要,您可以将其更改为int

1

这很简单,我希望我已经得到你的问题。请看下图:

#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; 
} 

,然后编译它在Linux上为:

gcc file.c 
./a.out 32 

程序应该打印您需要的值。

希望这会有所帮助。