using static_cast<datatype> to convert float to string c++
Solution 1
static_cast
is used to safely convert convertable types between each other, meaning types that either share the same base class or types that define conversion operators between each other. Although std::string
may define a constructor that takes in a float
(not sure) it is not cast-able from float
.
Solution 2
static_cast
can't be used in this way. static_cast
is used to cast -- in other words, pretend (in a way) that the thing passed in is actually something else. What you need to do is convert.
You don't need to convert a float
to cout
it -- just:
std::cout << value;
If you do need to convert, then there are many options:
Are just a few.
Solution 3
What you are trying to achieve is not casting, but converting a float to a string. There are several ways to do this.
This explains static_cast pretty well: Regular cast vs. static_cast vs. dynamic_cast
This explains how to transform a real number to a string: How do I convert a double into a string in C++?
And this is an answer everyone should read about various casts in c++: When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Solution 4
static_cast
is used to convert from one type to other convertible type. A conversion from float
to std::string
is not defined.
However, the way to obtain a string representation of a value is to call the function std::to_string()
:
int main()
{
float val = 10.0f;
std::string str = std::to_string( val );
}
But output streams are dessigned to work with non-string types too. So simply put the float into the stream:
std::cout << val;
10.0
Admin
Updated on June 05, 2022Comments
-
Admin almost 2 years
so this is my first "test" using static_cast, i have never done so, so please bear with me (i am very new to c++, stated 3 days ago)
// ConsoleApplication3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "iostream" #include "string" int main() { float value = 2.5f; int temp; std::cout << value; std::cout << static_cast<std::string>(value) ; std::cin.get(); }
it gives an error saying
error C2440: 'static_cast' : cannot convert from 'float' to 'std::string'
IntelliSense: no suitable constructor exists to convert from "float" to "std::basic_string, std::allocator>"
am I missing something?
-
Moo-Juice over 10 years+1. Perhaps also worth mentioning
boost::lexical_cast<>
as an alternative to achieve what they think they need to achieve :)