2

How can I convert all 4 characters into a float ? I can only convert the first character into an integer. Can you also give me some examples in your explanation. thanks

This is what I have tried so far.

void use_atof()
{

        char c[200];
        float val, v;

        strcpy(c ,"23.56,55.697,47.38,87.68");
        val = atof(c);
        printf("%f\n", val);
}
Akshay Hazari
  • 3,186
  • 4
  • 48
  • 84
user5771881
  • 97
  • 1
  • 9
  • Please review the format of your question. – user3743222 Jan 11 '16 at 05:38
  • you are not able to do like this. You have to do one by one. –  Jan 11 '16 at 05:57
  • 1
    You need to use 'character' more carefully. Each digit, decimal point and comma in the string is a character. You probably want to convert the 4 comma-separated numbers into 4 values. You'll need a loop. You'll need a function to find commas. You are using `atof()` so you don't care about errors in individual numbers — you'd be using `strtod()` if you did care. Have you looked at the functions in ``? Candidates that could be used include `strchr()`, `strpbrk()`, `strspn()`, `strcspn()`, `strstr()`, `strtok()`, and no doubt others. Some are better than others — don't use `strtok()`. – Jonathan Leffler Jan 11 '16 at 06:00
  • thanks for giving me different string candidates. – user5771881 Jan 11 '16 at 06:23

1 Answers1

3

You need to separate the input and call atof() on each value.

Below is a simple way to do this using strtok. note that it does destroy the input data (add NULL's) so if it's not acceptable you'll need to copy it or find another way (using strchr(), for example).

void use_atof()
{

    char c[200];
    float val, v;
    char *ptr;

    strcpy(c ,"23.56,55.697,47.38,87.68");
    ptr = strtok(c,",");
    while (ptr) {
        val = atof(ptr);
        printf("%f\n", val);
        ptr = strtok(NULL,",");
    }
}

EDIT:

Per request, an entire program (tested on Linux):

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

void use_atof(void);

int main()
{
    use_atof();
    exit (0);
}


void use_atof()
{

    char c[200];
    float val, v;
    char *ptr;

    strcpy(c ,"23.56,55.697,47.38,87.68");
    ptr = strtok(c,",");
    while (ptr) {
        val = atof(ptr);
        printf("%f\n", val);
        ptr = strtok(NULL,",");
    }
}