質問

How can I fill in a double or int array from a single, arbitrarily long, formatted (e.g. space delimited) keyboard line?

For instance:

Enter the elements of the array:
2 32 12.2 4 5 ...

should result in

=> array[0] = 2
=> array[1] = 32 etc.

I know that I can use scanf as follows, but that does not solve my problem, since each element should be entered one by one.

  /* Input data from keyboard into array */

  for (count = 1; count < 13; count++)
  {
      printf("Enter element : %d: ", count);
      scanf("%f", &array[count]);
  }

Thanks.

役に立ちましたか?

解決

I know that I can use scanf as follows, but that does not solve my problem, since each element should be entered one by one.

No. If you leave off the newlines, that would work perfectly fine.


Generally, it is a good idea to avoid using scanf(), though -- it's not the most intuitive function to use (so to say). How about using fgets() to read in the line then parse it using strtof()?

char buf[LINE_MAX];
fgets(buf, sizeof buf, stdin);

char *s = buf, *endp;
int i = 0;
for (i = 0; i < 13; i++) {
    array[i] = strtof(s, &endp);
    s = endp;
}

他のヒント

You can't have an array that will hold both int AND double values. You can either have an array of int, or an array of double. If there are likely to be any doubles in your input, you should just declare an array of double.

You have to also set a maximum size for the array, and stop reading when that number of elements is filled. In C, you cannot have an array of dynamic size. If you really need to dynamically change the data structure based on the number of values, you're better off using a linked list.

scanf() is not a great tool for this, as it won't distinguish the newline at the end of the input from the space that separates numbers. Use fgets() to read the entire line and then sscanf() to split it into array elements.

Here's how to use the array:

double ary[MAX_ARRAY_SIZE];    // MAX_ARRAY_SIZE being some defined value
char buffer [512];
char* ptr = buffer;
int i = 0;

printf ("Enter your values separated by spaces: ");
fgets (buffer, sizeof (buffer), stdin);

while (i < MAX_ARRAY_SIZE && ptr) {
    sscanf (ptr, "%lf", &ary[i]);
    ptr++;
    i++;
    ptr = strchr(ptr, '\040');
}

You can do some work on variable initialization etc.. But this will do what you ask.

#include <ansi_c.h>

int main(void)
{
    char hold[20][10];
    double arr[20];//change size as necessary
    char *buf;
    char *toss;
    int i=-1, j=0;
    buf = malloc(260);
    toss = malloc(260);

    fgets(buf, 260, stdin);
    buf = strtok(buf, " ");
    while(buf)
    {
        strcpy(hold[++i], buf);
        arr[i] = strtod(hold[i], &toss);
        buf = strtok(NULL, " ");
    }

    for(j=0;j<i;j++)
    {
        printf("arr[%d]=%f\n", j, arr[j]);  
    }

    getchar();

    return 0;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top