[英]Passing Two dimensional array to C++ using command line
I am having a requirement where in I need to call a C++ application from command line and need to pass a two dimensional array of int type to it. 我有一个要求,我需要从命令行调用C ++应用程序,并且需要将int类型的二维数组传递给它。 Can anyone please let me know how to do that, and how to interpret it in C++ application using argv parameter 任何人都可以让我知道如何执行此操作,以及如何使用argv参数在C ++应用程序中对其进行解释
thanks in advance. 提前致谢。
In argv
you can pass only a one dimensional array, containing strings, it's 在argv
您只能传递一个包含字符串的一维数组,它是
char* argv[]
So, you can't really pass 2D array, but you can "simulate" it. 因此,您不能真正传递2D数组,但可以“模拟”它。
For example, pass 2 parameters, saying what are the sizes of the matrix - number of rows and number of columns and then pass all elements, one by one. 例如,传递2个参数,说矩阵的大小是多少-行数和列数,然后将所有元素一一传递。
Then parse the arguments in your program, knowing what format you will use. 然后在您的程序中解析参数,知道您将使用哪种格式。
For example: if you want to pass 例如:如果您想通过
1 2 3
4 5 6
you may run your program like this: 您可以这样运行程序:
./my_program 2 3 1 2 3 4 5 6
This way, you'll know, that argv[1]
is the number of rows, argv[2]
s the number of columns and them all elements of the 2D array, starting from the upper left corner. 这样,您将知道argv[1]
是行数, argv[2]
是列数,它们是2D数组的所有元素,从左上角开始。
Don't forget, that argv
is array, containing char*
pointers. 不要忘记, argv
是数组,包含char*
指针。 In other words, you'll need to convert all parameters int
s. 换句话说,您需要转换所有参数int
。
I would recommend passing a file as the only argument. 我建议将文件作为唯一参数传递。 Or data in the same format on stdin as @j_random_hacker suggests. 或与@j_random_hacker建议的标准格式相同的数据。 If no human needs to edit it, it could be a binary file. 如果没有人需要编辑它,则它可能是二进制文件。 One possible format: 一种可能的格式:
4 bytes = size of first dimension 4 bytes = size of second dimension 4 bytes * size of first * size of second = contents of array 4个字节=第一个维度的大小4个字节=第二个维度的大小4个字节*第一个大小*第二个大小=数组的内容
When reading, everything is aligned. 阅读时,所有内容都对齐。 Just read every four byte int and interpret as above. 只需读取每四个字节的int并按上述解释即可。
If it needs to be human readable I would do csv or space-delimited. 如果需要人类可读,则可以使用csv或以空格分隔。 There would be no need to specify the dimensions in that case because each row ends in newline. 在这种情况下,无需指定尺寸,因为每一行都以换行符结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.