浮点数 C++,如何在末尾为数组的每个元素添加 "f"
Floating numbers C++ , How to add "f" in the end for each element of array
我刚刚打开 filename.file ,将每个浮点数保存在向量 "vertices" 中,但它们被保存为整数 numbers.Need 以将所有数字正确转换为浮点数。
例如:从“1”到“1.00000f”或至少从“1”到“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] << " ";
}
/* 每个元素
1个
-1
1个
...
// 但是这些数字应该是这样保存的
1.000000f
-1.000000f
1.000000f
...
*/
听起来你想要的东西的顺序是:
std::cout << std::fixed << std::setprecision(5) << value << "f";
例如:
float values[] = { 1.0f, -1.0f, 1.0f };
for (auto const &value : values)
std::cout << std::fixed << std::setprecision(5) << value << "f\t";
结果:
1.00000f -1.00000f 1.00000f
我刚刚打开 filename.file ,将每个浮点数保存在向量 "vertices" 中,但它们被保存为整数 numbers.Need 以将所有数字正确转换为浮点数。 例如:从“1”到“1.00000f”或至少从“1”到“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] << " ";
}
/* 每个元素 1个 -1 1个 ...
// 但是这些数字应该是这样保存的
1.000000f -1.000000f 1.000000f ... */
听起来你想要的东西的顺序是:
std::cout << std::fixed << std::setprecision(5) << value << "f";
例如:
float values[] = { 1.0f, -1.0f, 1.0f };
for (auto const &value : values)
std::cout << std::fixed << std::setprecision(5) << value << "f\t";
结果:
1.00000f -1.00000f 1.00000f