📜  C++中的std :: to_wstring

📅  最后修改于: 2021-05-30 03:37:29             🧑  作者: Mango

此函数用于将数值转换为宽字符串,即它将数据类型(int,long long,float,double)的数值解析为宽字符串。它返回一个宽字符串,其数据类型为wstring,表示在函数传递的数值。在此函数数据类型在内部类型转换为wstring数据类型,并绕过数值作为其参数,我们可以获取字符串的wstring类型,作为回报,其中将数值类型转换为所需的数据类型。

句法 :

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++ code to convert numerical value
// to wide string data tpye
// using the to_wstring function
  
// These header files contains wcout, 
// wstring and to_wstring
#include  
#include      
using namespace std;
  
//Driver code
int main ()
{
  
// Data types to be typecasted
float x = 3.1415926;
int a = 5 , b = 9;
double y = 6.29;
  
// numercial values being typecasted into wstring 
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";
  
// Printing the typecasted wstring 
wcout << pi << L'\n';
wcout << perfect << L'\n';
wcout << num <

输出:

Pi is 3.141593
14 is a number
2.002169is division of two numbers

应用范围:
它可以用于计算要在报表语句(例如平均值)中使用的值,因此我们无需为此编写任何语句,我们可以直接使用此函数转换数值。

示例:假设一个部门的HOD正在为其部门中的部门数量提交报告,并且他必须避免数据类型转换,因此他可以使用to_wstring函数来完成此特定任务。
下面是实现:

// These header files contains wcout and wstring
#include  
#include      
  
using namespace std;
  
// Driver code
int main ()
{
  
// Data types to be typecasted
int a = 600 , b = 150;
  
// numercial values being typecasted into wstring 
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";
  
// Printing the typecasted wstring 
wcout << rep << L'\n';
wcout << sec_rep << L'\n';
return 0;
}

输出:

Number of section =  4
150 is the number of students in each section

在上面的示例中,我们不需要每次都进行数据类型转换,但是借助此函数,可以避免外部类型转换,这对于系统是有利的,因为外部类型转换比功能性标记需要更多的时间。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”