2

我只想知道这些线实际上做了什么。

int main(int argc, char *argv[])

尤其是这个:

int n = atoi (argv[1]);

我在一本书中读到这一点,但我无法理解这些行。

4

3 回答 3

11

这会将第一个命令行参数转换为整数。例如,如果你这样调用你的程序

./a.out 123

然后n123

请注意,在访问之前argv[1]必须检查argc是否大于1,即检查是否已在命令行上将至少一个参数传递给您的程序。

于 2013-03-30T12:04:48.277 回答
0

argc 是参数的计数。argv 是参数变量的缩写。它将包含命令行上传递的所有参数。argv[1] 包含第一个参数,因此 atoi(argv[1]) 会将第一个参数转换为 int

于 2013-03-30T12:07:09.027 回答
0
int main(int argc, char *argv[])

The first parameter to main, argc, is the number of command line arguments. For example, if the user enters:

./a.out 5 6 7

argc will be 4 (a.out counts as one of the command line arguments, and 5, 6, and 7 as three more).

argv is an array of strings):

        -----
argv[0]:| *-|"./a.out"
        -----
argv[1]:| *-| "5"
        -----
argv[2]:| *-| "6"
        -----
argv[3]:| *-| "7"
        -----
argv[4]:| *-| "\0"
        -----

atoi() functionconverts string data type to int data type. since commandline arguments (argv[]) can only take strings, you need to convert that stringintoarithmetic numbersin order to use it as such. Theatoi` (alphabetical to integer) does that for you where it takes in any string and converts the numbers inside the string into arithmetic numbers.

于 2021-10-31T06:43:58.097 回答