brostone51
brostone51

Reputation: 125

How to read number input of unsure length?

I've been stuck on a problem for awhile, I need to read input from the user in the form,

5 1.2 2.3 3.4 4.5 5.6

where the first integer is the number of floats to expect, and then the floats following are the values I need to store in an array of that size. The code I have that keeps returning an error is,

...
int i = 0, j, k;
float value, *ptr;
// For every element in inputArr...
while (i < inputLength) {
    printf("Enter the number of values in this data set, followed by the values: ");
    // Get the int value for array creation...
    scanf("%d ", &j);
    printf("%d", j);
    // Save it for the calculations later.
    *(lengths + i) = j;
    // Create dynamic array of floats.
    *(inputArr + i) = calloc(j, sizeof(float));
    ptr = *(inputArr + i);
    // For the rest of the input read the floats and place them.
    k = 0;
    while (k < j-1) {
        scanf("%f ", &value);
        *(ptr + k) = value;
        k++;
    }
    scanf("%f\n", &value);
    *(ptr + j - 1) = value;
    i++;
}

This throws a segmentation fault when I enter in the input above. Can someone help me out by telling me what I'm doing incorrectly?

Upvotes: 0

Views: 69

Answers (1)

Ashalynd
Ashalynd

Reputation: 12563

You do not have to include spaces and end-of-strings in your scanf calls.

scanf("%d", &j);

i/o

scanf("%d ", &j);

scanf("%f", &value);

i/o

scanf("%f\n", &value);

etc.

Upvotes: 1

Related Questions