我只想知道这些线实际上做了什么。
int main(int argc, char *argv[])
尤其是这个:
int n = atoi (argv[1]);
我在一本书中读到这一点,但我无法理解这些行。
我只想知道这些线实际上做了什么。
int main(int argc, char *argv[])
尤其是这个:
int n = atoi (argv[1]);
我在一本书中读到这一点,但我无法理解这些行。
这会将第一个命令行参数转换为整数。例如,如果你这样调用你的程序
./a.out 123
然后n会123。
请注意,在访问之前argv[1]必须检查argc是否大于1,即检查是否已在命令行上将至少一个参数传递给您的程序。
argc 是参数的计数。argv 是参数变量的缩写。它将包含命令行上传递的所有参数。argv[1] 包含第一个参数,因此 atoi(argv[1]) 会将第一个参数转换为 int
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.