提供整数数组作为命令行的输入
我正在编写一个程序来访问库中的装箱算法函数,自从大学以来我就没有用它做太多事情,所以我的 C 有点生疏。我调用的函数要求我传入 3 个不同的整数数组。我将从命令行调用它。我应该使用argv吗?还是标准输入?每个输入数组可能包含 50 到 100 个元素。无论哪种方式,我想我都必须编写一些东西来解析字符串并将它们放入数组中,有没有一种简单的方法可以做到这一点?
I'm writing a program to access a bin packing algorithm function from a library, I haven't done much with it since college so my C is a bit rusty. The function I'm calling requires I pass in 3 different integer arrays. I'll be calling this from the command line. Should I use argv? Or STDIN? The input arrays could potentially be 50 to 100 elements each. Either way I suppose I will have to write something to parse the strings and get them into arrays, is there an easy way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于大数组,我宁愿使用标准输入,因为通常操作系统对可以拥有的参数数量有限制。
您还需要某种输入格式。假设第一个数字 n 是第一个数组中的元素数量,后面是元素值,依此类推。然后我会做这样的事情:
你明白了总体想法。您要么必须自己实现
read_number
,要么在网上查找有关如何执行此操作的示例。您将需要以某种方式辨别各个数字,例如通过将每个数字解析到下一个空白字符。然后您可以用空格字符分隔标准输入上的每个数字。例如,您可以使用下面@ypnos 建议的 scanf 解决方案。
For big arrays, I'd rather use standard input, as there are usually operating system limits to how many arguments you can have.
You will also need some kind of input format. Let's say the first number
n
is the number of elements in the first array, followed by the element values, and so on. Then I'd do something like:You get the general idea. You'd either have to implement
read_number
yourself or find examples on the net on how to do it. You will need to discern individual numbers somehow, e.g. by parsing each digit up to the next white space character. Then you can separate each digit on stdin by space characters.For instance, you can use @ypnos suggested scanf solution below.
对于该数量的元素,您应该使用标准输入。无论如何,没有人会手写它们,并且
./program < file
就这么简单。解析对于scanf来说没什么大不了的。只需定义您的输入应包括形成数组的所有数字之前的元素数量。然后您可以
scanf("%d", &elemcount)
,然后再次使用scanf
对 elemcount 进行 for 循环。它的美妙之处在于 scanf 将处理用户可能放入元素数量和其他数字之间的所有空格、换行符等。
For that amount of elements you should use stdin. Nobody will type them in by hand anyway and
./program < file
is as easy as it gets.The parsing is no big deal with scanf. Just define that your input should include the number of elements before all the numbers forming an array. Then you can
scanf("%d", &elemcount)
, and then for-loop over elemcount, again usingscanf
.The beauty of it is that scanf will deal with all the whitespaces, newlines etc. the user may put in between the numbers of elements and the other numbers.