0

I want to convert string of multiple decimal numbers, into float. In my case, when the program starts, the user is asked to write some numbers, and it's saved into array (payment), but I need to work with these numbers after that. What's the right way to do it?

EDIT: The main problem is that I don't know how to read a sequence of those numbers, e.g. Insert payment: "1 2 3", I want my result to be 1 2 3 and my actual result is just 1.

This is my code.

 int main(){

    char payment[100];
    printf("Insert money for payment: ");
    fgets(payment,100,stdin);
    printf("Insert money for payment: %s\n", payment);


    return 0;
}

Thank you in advance

Amittai Shapira
  • 3,749
  • 1
  • 30
  • 54
Willy
  • 21
  • 3
  • `fgets();` is a good first step. Research `sscanf()` as in `sscanf(..., "%f %f %f", ...)`. Also explain more next time, Here, why would input "1 2 3" make sense for a _payment_? – chux - Reinstate Monica Nov 17 '18 at 14:18

1 Answers1

0

You can use sscanf to do that.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
    float paymentf;
    char payment[100];
    printf("Insert money for payment: ");
    fgets(payment,100,stdin);
    printf("Insert money for payment: %s\n", payment);
    sscanf( payment, "%f", &paymentf );
    printf("Payment in float = %f\n", paymentf );
    return(0);
}
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • And If I want to write more numbers? Like: (Insert payment: 1 2 3 10) Then the float " paymentf " is just that first number and not all of them. I don't know how to read and convert more numbers – Willy Nov 17 '18 at 11:34
  • Because later I need to check if the numbers are only the allowed one and I will have to count them together, but thats easy, I'm just stuck on this problem... – Willy Nov 17 '18 at 11:36