Alex Tsypurdei
Alex Tsypurdei

Reputation: 51

Floating numbers C++ , How to add "f" in the end for each element of array

I just opend filename.file , saved each floating number in vector "vertices" but they are saved as ineteger numbers.Need to convert all numbers correctly to float. For example : from "1" to "1.00000f" or atleast from "1" to "1.0f".

/////filename.file
...
v 1.000000 1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 1.000000 1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 -1.000000
v -1.000000 -1.000000 -1.000000
v -1.000000 1.000000 1.000000
...
//////


std::vector<float> vertices;

std::ifstream file(filename); 

    std::string line;

    while (std::getline(file, line))
    {

        std::istringstream iss(line);

        std::string result;

        if (std::getline(iss, result, ' '))
        {

            if (result == "v")
            {



                while (std::getline(iss, token, ' '))
                {
                    std::istringstream iss1(token);

                    if (std::getline(iss1, word))
                    {
                        float word_float = std::stof(word);

                        //std::cout << word_float << std::endl;
                        vertices.push_back(word_float);
                    }
                }
            }
        }
    }

//Look what I got
for(std::size_t i = 0 ; i < vertices.size(); i++) {
 std::cout << vertices[i] << " ";
}

/* Each element 1 -1 1 ...

// But these numbers should be saved exactly so

1.000000f -1.000000f 1.000000f ... */

Upvotes: 0

Views: 310

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490408

It sounds like you want something on the order of:

std::cout << std::fixed << std::setprecision(5) << value << "f";

for example:

float values[] = { 1.0f, -1.0f, 1.0f };

for (auto const &value : values)
    std::cout << std::fixed << std::setprecision(5) << value << "f\t";

Result:

1.00000f    -1.00000f   1.00000f

Upvotes: 1

Related Questions