开发者

Provide integer arrays as input from command line

开发者 https://www.devze.com 2023-03-06 02:26 出处:网络
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 diffe

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 somet开发者_如何学运维hing to parse the strings and get them into arrays, is there an easy way to do that?


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:

#include <stdlib.h>
#include <stdio.h>

int main()
{
  // you need to implement read_number yourself
  int n = read_number(stdin);

  // allocate array
  int *array = (int*) malloc(n*sizeof(int));

  // read n numbers into array
  for ( int i=0; i < n; ++i )
    array[i] = read_number(stdin);

  // and so on...
}

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.


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 using scanf. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消