std::to_wstring in c++
Last Updated :
14 Sep, 2021
This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function. In this function data type is being internally typecasted to the wstring data type and bypassing the numerical value as its parameter we can obtain a wstring type of string in return where the numerical value has been typecasted to the desired data type.
Syntax :
wstring to_wstring (int val);
wstring to_wstring (long long val);
wstring to_wstring (float val);
wstring to_wstring (double val);
Parameters :
val :This is the numerical value that is to be converted to the wide string.
Return Value :
It returns the passed numerical value into the wide string of data type wstring.
C++
#include <iostream>
#include <string>
using namespace std;
int main ()
{
float x = 3.1415926;
int a = 5 , b = 9;
double y = 6.29;
wstring pi = L "Pi is " + to_wstring(x);
wstring perfect = to_wstring(a+b) +
L " is a number" ;
wstring num = to_wstring(y/x) +
L "is division of two numbers" ;
wcout << pi << L '\n' ;
wcout << perfect << L '\n' ;
wcout << num <<L '\n' ;
return 0;
}
|
Output:
Pi is 3.141593
14 is a number
2.002169is division of two numbers
Applications :
It can be used for calculation to be used in report statement such as average value so we need not write any statement for this purpose and we can directly use this function to convert numerical values.
Example: Suppose the HOD of a department is filing a report for number of sections in his department and he has to avoid data type casting so he can use to_wstring function to do this particular task.
Below is the implementation :
C++
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int a = 600 , b = 150;
wstring rep = L "Number of section = " + to_wstring(a/b);
wstring sec_rep = to_wstring(b) +
L " is the number of students in each section" ;
wcout << rep << L '\n' ;
wcout << sec_rep << L '\n' ;
return 0;
}
|
Output:
Number of section = 4
150 is the number of students in each section
In the above example we need not typecast the data type every time but with the help of this function external typecasting is avoided which is beneficial for the system as external typecasting takes more time then the stl functions.
Share your thoughts in the comments
Please Login to comment...