Converting float to char array in C/C++

Asked

Viewed 11,111 times

6

I recently took a test and there was a question that asked for a number like 123.456 was shown as 321.456. I thought the best solution would be to convert this to an array of char and then create an algorithm to print position by position, using pointers, with the . and the \0 served as stop tokens. I implemented the algorithm but don’t know how to make this one float to an array of char so that each digit is in one position.

How do I convert a float in an array of char in C/C++?

I was also curious to know how to do this with other guys. int for char, byte for char and do the opposite process as well (char for float).

4 answers

8

In C, you can do:

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

int main(){

    float valor = 123.456;
    char convertido[16];
    sprintf(convertido, "%.3f", valor);

    printf("A float convertido = %s", convertido);

    return 0;
}

Detail for the %.3f, indicating 3 decimal places. Using only %f can occur conversions beyond what you want type 123.45600001 in his char[];

The sprinf may be used for other types as well (int, char), you just have to change the parameter %f for what you want.


In C++11:

#include <iostream>
#include <string>

int main(){

    float valor = 123.456;
    std::string resultado = std::to_string(valor);
    const char* convertido = resultado.c_str();

    std::cout << "O float convertido = " << convertido << std::endl;

    return 0;
}

It also serves to int, char and etc.


In older versions of C++:

#include <iostream>
#include <string>
#include <sstream>

template <typename T>
std::string to_string(const T a_value)
{
    std::ostringstream out;
    out << a_value;
    return out.str();
}

int main(){

    float valor = 123.456;

    std::string resultado = to_string(valor);
    const char* convertido = resultado.c_str();
    std::cout << "O float convertido = " << convertido << std::endl;
    std::cin.get();

    return 0;
}
  • Excellent answer. Could you tell me how the implementation of the sprintf function is done? I tried to find it on the internet but did not find.

  • The implementation is quite large. You can see the gcc version if you download the glibc and search in stdio-common. Research on lexical analysis also has to do with.

  • 1

    No need to explicitly pass the template argument to the to_string (last example).

7


Although the other answers solve the problem, I put this question to the test precisely to force engineering academics to think about a mathematical solution. This is simpler, more natural and more efficient than calling functions to manipulate strings.

Notice that what this exercise actually called for was to change the digits of the unit and the hundred digits of the number. Well, this can be accomplished as follows:

float num = 123.456f;
int parte_inteira = num;
float parte_decimal = num - parte_inteira;

int digito_centena = parte_inteira / 100;
int digito_dezena = parte_inteira % 100 / 10;
int digito_unidade = parte_inteira % 10;

float num_invertido = (digito_unidade*100) + (digito_dezena*10) + digito_centena + parte_decimal;
printf("%0.3f\n", num_invertido);

I believe the above code is quite educational and so I will not go into more detail.

Of course, these operations could be performed on the same line with the help of explicit conversions of data types (cast), saving variable declarations:

float num_invertido = (((int)num % 10) * 100) +
                      (((int)num % 100 / 10) * 10) +
                       ((int)num / 100) +
                       (num - (int)num);
printf("%0.3f\n", num_invertido);
  • 1

    Thank you. I had not thought of this solution. Quite interesting. =)

  • 5

    My Pleasure! Be careful who you cuss around here, hehe. ;)

  • Just to take your foot: was it clear in the statement that the goal was to swap the two digits, and that this should be done by mathematical operations? And what would be the practical use of reversing the position of the hundred and the unity? Nevertheless, +1 in the above commentary for good humor. I don’t vote for the answer because language is not my thing (although I understand the solution).

  • 2

    @bfavaretto This was just an item in a more elaborate question, and the students had complete freedom to solve this little problem in the way that was most convenient for them. The purpose of this task was exercise logical reasoning and improve perception: There was another question on the test that partially answered this challenge. Anyway, this arithmetic technique of extracting specific digits from a number is widely used in the development of embedded systems, especially when working with real-time data streams, as is the case with DTV transmissions.

5

In pure C you just need to use the function sprintf which works in the same way as the printf but instead of sending the output to the console you can save it in a variable.

In C

#include <stdio.h>

#define WORD_LENGTH 64

int main(int argc, char *argv[])
{
    float value = 123.456F;
    char str[WORD_LENGTH];

    sprintf(str, "%.3f", value);

    printf("%s\n", str);

    return 0;
}

In C++ you have the freedom to use the same solution as in C, but it also has its own exit.

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])
{
    float value = 123.456F;
    stringstream stream;
    string output;

    stream << value;

    output = stream.str();

    cout << output << endl;

    return 0;
}

Already in C++11 the latest version, you can simply use.

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    float value = 123.456F;
    string output = std::to_string(value);

    cout << output << endl;

    return 0;
}

3

A possible solution would be:

float flt = 123.456;
char mybuff1[50];
sprintf (mybuff1, "%f", flt);
char *c [] = {mybuff1};

There is a post explaining better in stackoverflow.com: how can i assign float value to char* c[] array I hope it helps.

  • Note: If it doesn’t work let me know.

  • 2

    Better to use snprintf to avoid buffer overflow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.