C++中的std:to_string和std:to_wstring的详细指南

1,951 阅读2分钟

在这篇文章中,我们探讨了C++ STL中的函数std:to_string和std::to_wstring以及字符串和wstring(宽字符串)的区别:

内容表

  • std::to_string
  • std::to_wstring
  • 字符串和wstring之间的区别

简而言之:std:to_string用于将数字数据类型转换为字符串,而std::to_wstring则用于将数字数据类型转换为宽字符串(wstring)。

std::to_string

在C++中,std::to_string是一个模板,用于将任何数据类型转换为
字符串。

它可以用在所有的数据类型上,比如:

  1. int
  2. 浮点数
  3. 双数
  4. 长双

使用的语法如下:

string to_string(datatype variable name)

例如,双数的转换可按以下方式进行:

转换的代码

#include <iostream>
#include<bits/stdc++.h>

using namespace std;

int main()
{
  double a=92.863;
  char c[10]="hello";
  
   std::string str1 = std::to_string(a);
   // double a is converted into string 
         std::cout << str1<<endl ;
         cout<<(a);
         cout << typeid(a).name() << endl;
       
    return 0;
    
  
}

输出

92.863000
92.863d

typeid

现在要检查数据类型是否转换为字符串,我们可以使用
type id的语法如下
typeif(变量名).name()

复杂度
这是一个可以在O(1)时间内完成转换的过程

应用
最常见的应用之一是在转换后找出字符串中某个特定元素的索引:

#include <iostream>
#include<bits/stdc++.h>

using namespace std;

int main()
{
 // Converting number to string
    std::string str = std::to_string(732);
 
    // Finding 7 in the number
    std::cout << "7 is at position " << str.find('7') + 1;
       
    return 0;
}

OUTPUT

7 is at position 1

我们可以看到在str.find()之后添加了+1,因为它的索引是从0开始的。

std::to_wstring

这个函数用来将数值转换为宽字符串,也就是说,它将int、float、char、double等数据类型的数值解析为宽字符串。简而言之,它通过对存储在其中的数字值进行类型转换,将所有数据类型转换为W字符串数据类型。

转换的语法
语法:

wstring to_wstring (int variable name);

它的唯一输入是变量名,结果是它将给定的数据转换为wstring

转换的代码

#include <iostream>
#include <string>    
using namespace std;
 

int main ()
{
 

float x = 3.1415926;
int a = 5 , b = 9;
double y = 6.29;
 
// numerical values being typecasted into wstring

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 << perfect << L'\n';
wcout << num <<L'\n';
return 0;
}
14 is a number
2.002169 is division of two numbers

为了打印出数据,我们使用wcout而不是cout,因此我们必须包含#include<algorithm> ,以便正常运行。

应用
它可以用于报告语句中的计算,如平均值,我们可以直接使用这个函数来转换数值,而不是计算它。

// These header files contains wcout and wstring
#include <iostream>
#include <string>	

using namespace std;

// Driver code
int main ()
{


int a = 60 , b = 45;


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;
    
}

输出

number of section is 1
45 is the number of student in the class.

字符串和wstring的区别

  • std::string持有char_t(char)的集合来表示一个字符串。char类型严格来说只能容纳标准的ASCII字符(0-255)。
  • std::wstring持有wchar_t (wide chars)的集合来表示一个字符串。wchar_t类型持有UTF(2/4字节)格式的字符。它们被用来存储unicode。

在平行线上,你可以区分std::cout和std::wcout,你可以理解std::cout不能与std::wstring一起工作。

通过OpenGenus的这篇文章,你一定对C++中的std:to_string和std::to_wstring有了完整的概念。