通常需要将整数数据类型转换为字符串变量。C ++具有自己的库函数to_string(),该函数将任何数字值转换为其相应的字符串类型。例如,123转换为“ 123”。
前123是整数,而“ 123”是字符串值
int i = 123;
字符串s = to_string(i);
原型:
string to_string(int/long/long long);
参数:数值
返回类型:字符串
例
Like we define and declare, int i=5; string s=to_string(i); if(s=="5") cout<<"converted to string"; else cout<<"Failed to convert.";
请记住,需要在“”下定义一个字符串变量(文字)。“ a”是字符,而“ a”是字符串。
需要的头文件:
#include <string> Or #include <bits/stdc++.h>
C ++程序将整数转换为字符串
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cout<<"Input integer to convert\n";
cin>>n;
string s=to_string(n);
cout<<"Converted to string: "<<s<<endl;
return 0;
}输出结果
Input integer to convert 23 Converted to string: 23