Avi Shah
Avi Shah

Reputation: 109

C++ equivalent of C# Convert

In C#, there is a class with static methods for type conversions:Convert.ToUInt16(). Is there a C++ equivalent of these methods. I know a few, like to_string from string.h, but it would be better if all of these type conversions were in one place.

Upvotes: 1

Views: 232

Answers (2)

darune
darune

Reputation: 10962

Pre you can just do:

short int i;
std::istringstream iss{int_string};
iss >> i;

With you may also use std::from_chars - the preferred method. See also this answer.

Upvotes: 3

Caleth
Caleth

Reputation: 62576

if all of these type conversions were in one place

Conversions to or from std::string are in namespace std, whilst conversions between arithmetic types are casts.

std::cout << std::to_string(1.2)
int i;
auto num = "1"s;
std::from_chars(num.begin(), num.end(), i);
std::cout << i;
std::cout << static_cast<std::uint16_t>(1.2);

For conversions of user-defined-types, rather than defining an interface like IConvertible, C++ allows you to define operator int et.al. in your class.

Upvotes: 4

Related Questions