2

4 文字すべてを float に変換するにはどうすればよいですか? 最初の文字のみを整数に変換できます。また、説明の中でいくつかの例を教えてください。ありがとう

これは私がこれまでに試したことです。

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);
}
4

1 に答える 1

3

入力を分離し、各値で atof() を呼び出す必要があります。

以下は、strtok を使用してこれを行う簡単な方法です。入力データを破棄する (NULL を追加する) ことに注意してください。受け入れられない場合は、コピーするか、別の方法 (たとえば、strchr() を使用) を見つける必要があります。

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,",");
    }
}

編集:

リクエストごとに、プログラム全体 (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,",");
    }
}
于 2016-01-11T06:16:27.757 に答える