Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C scanf - unknown array size

Tags:

c

scanf

I want to read values (float) into an array but I don't know number of values.

My input is this

Enter values: 1.24 4.25 1.87 3.45 .... etc

How can I load this input to an array? I know that input ends when enterring 0 or EOF.

while(0 or EOF){
   scanf("%f", &variable[i])
   i++;
}

Thank you.

like image 468
user3376620 Avatar asked Jun 17 '26 05:06

user3376620


2 Answers

You can dynamically allocate the array and then reallocate the memory for it when the previously allocated buffer is full. Note that the conversion specifier %f in the format string of scanf reads and discards the leading whitespace characters. From the man page of scanf -

scanf returns the number of items successfully matched and assigned which can be fewer than provided for, or even zero in the event of an early matching failure. The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.

This means that scanf will return EOF only when it encounters EOF as the first input when it is called because EOF must be preceded with a newline '\n' else it won't work (depending on the OS). Here's a small program to demonstrate how you can do it.

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

int main(void) {
    size_t len = 4;
    float *buf = malloc(len * sizeof *buf);

    if(buf == NULL) {     // check for NULL        
        printf("Not enough memory to allocate.\n");
        return 1;
    }

    size_t i = 0;
    float *temp; // to save buf in case realloc fails

    // read until EOF or matching failure occurs
    // signal the end of input(EOF) by pressing Ctrl+D on *nix
    // and Ctrl+Z on Windows systems

    while(scanf("%f", buf+i) == 1) { 
        i++;
        if(i == len) {               // buf is full
            temp = buf;
            len *= 2;
            buf = realloc(buf, len * sizeof *buf);  // reallocate buf
            if(buf == NULL) {
                printf("Not enough memory to reallocate.\n");
                buf = temp;
                break;
            }
        }
    }

    if(i == 0) {
        printf("No input read\n");
        return 1;
    }

    // process buf

    for(size_t j = 0; j < i; j++) {
        printf("%.2f ", buf[j]);
        // do stuff with buff[j]
    }

    free(buf);
    buf = NULL;

    return 0;
}
like image 114
ajay Avatar answered Jun 18 '26 18:06

ajay


I guess your actual concern is the unknown number of floats that user is going to input. You can use pointer to float, do malloc for some predefined size, if your limit has reached while taking an input then do a realloc to increase the memory. You need to take care of previously accepted data while doing a reaccloc.

like image 31
Smitt Avatar answered Jun 18 '26 18:06

Smitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!