C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ int转换string

有三种将整数转换为字符串的方法:
C++ int到字符串 通过使用stringstream类 使用to_string()方法 通过使用boost.lexical转换

使用stringstream类将整数转换为字符串。

以下是用于插入或提取数据的运算符:
运算符>>: 它从流中提取数据。 运算符<<: 它将数据插入流中。
让我们通过示例来了解运算符的概念。
在下面的语句中,< <插入运算符将100插入流中。
stream1 << 100;
在下面的语句中,>>提取运算符从流中提取数据并将其存储在'i'变量中。
stream1 >> i;
让我们通过一个例子来理解。
#include <iostream>
#include<sstream>
using namespace std;
int main() {
  int k;
  cout<<"Enter an integer value";
  cin>>k;
  stringstream ss;
  ss<<k;
  string s;
  ss>>s;
  cout<<"\n"<<"An integer value is : "<<k<<"\n";
  cout<<"String representation of an integer value is : "<<s; 
}
输出
将C++ int转换为字符串
在上面的示例中,我们创建了 k 变量,并希望将k的值转换为字符串值。我们使用了stringstream类,该类用于将k个整数值转换为字符串值。反之亦然,也就是说,也可以仅通过使用stringstream类将字符串转换为整数值。
让我们了解通过将字符串转换为数字的概念。例子。
#include <iostream>
#include<sstream>
using namespace std;
int main()
{
  string number ="100";
  stringstream ss;
  ss<<number;
  int i;
  ss>>i;
  cout<<"The value of the string is : "<<number<<"\n";
  cout<<"Integer value of the string is : "<<i;
}
输出
C++ int转换为字符串

使用to_string()方法将整数转换为字符串。

to_string()方法接受单个整数并转换整数值或其他数据
让我们通过一个示例来理解:
#include <iostream>
#include<string>
using namespace std;
int main()
{
 int i=11;
 float f=12.3;
string str= to_string(i);
string str1= to_string(f);
cout<<"string value of integer i is :"<<str<<"\n";
cout<<"string value of f is : "<< str1;
}
输出
C++ int转换为字符串

通过使用boost.lexical强制转换将整数转换为字符串。

boost.lexical强制转换提供了强制转换运算符,即boost.lexical_cast,它将字符串值转换为整数值,反之亦然。
让我们通过示例了解整数到字符串的转换。
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
int main()
{
 int i=11;
 string str = boost::lexical_cast<string>(i);
cout<<"string value of integer i is :"<<str<<"\n";
}
输出
将C++ int转换为字符串
在上面的示例中,我们使用lexical_cast()函数将'i'变量的值转换为字符串值。
让我们通过一个示例来理解将字符串转换为整数的情况。
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
int main()
{
string s="1234";
 int k = boost::lexical_cast<int>(s);
cout<<"Integer value of string s is : "<<k<<"\n";
}
输出
将C++ int转换为字符串
在上面的示例中,我们已使用lexical_cast()函数将字符串值转换为整数值。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4