Home > OS >  How to read in multiple floats on one line and then add them to an array?
How to read in multiple floats on one line and then add them to an array?

Time:10-27

I am trying to read in a line of floating point values like

1.1 -100.0 2.3

and I need to store these in an array. I am using the fgets() method to convert the input into a string. Is there anyway I can use this string to populate a float array with the values? Or is there a better way to do this?

#include <stdio.h>

int main(){
    char input [500];
    float values [50];
    fgets(input, 500, stdin);
// now input has a string with all the values
// and the values array needs to be filled with the values
}

CodePudding user response:

You can apply sscanf for the inputted string.

Here is a simplified demonstration program.

#include <stdio.h>

int main(void) 
{
    char input[20];
    float values[3];
    
    fgets( input, sizeof( input ), stdin );
    
    size_t n = 0;
    char *p = input;
    
    for ( int pos = 0; n < 3 && sscanf( p, "%f%n", values   n, &pos ) == 1; p  = pos )
    {
          n;
    }
    
    for ( size_t i = 0; i < n; i   )
    {
        printf( "%.1f ", values[i] );
    }
    
    putchar( '\n' );
    
    return 0;
}

If the inputted string is

1.1 -100.0 2.3

then the output of the array values is

1.1 -100.0 2.3
  • Related