to_string()是<string>标头的库函数,用于将数值(数字)转换为字符串。
语法:
string to_string(numberic_value);
这里,
-
string是返回类型,即函数返回一个字符串对象,其中包含字符串格式的数字值。
-
numbric_value是可以为整数,浮点数,长整数,双精度数的数字。
示例
#include <iostream>
#include <string>
using namespace std;
int main ()
{
//定义不同类型的数据类型
int intVal =12345;
float floatVal = 123.45f;
long longVal = 123456789;
//将值转换为字符串以打印
cout<<"intVal (string format) : "<<to_string (intVal) <<endl;
cout<<"floatVal (string format) : "<<to_string (floatVal) <<endl;
cout<<"floatVal (string format) : "<<to_string (longVal) <<endl;
return 0;
}
输出结果
intVal (string format) : 12345 floatVal (string format) : 123.449997 floatVal (string format) : 123456789
C++语法】.c_str()函数
1. c_str()理论介绍
c_str():生成一个const char*指针,指向以空字符终止的数组。
2. 需要包括头文件
#include<csting>
using namespace std;
int main()
{
//string-->char*
//c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同
//这个数组的数据是临时的,当有一个改变这些数据的成员函数被调用后,其中的数据就会失效。
//因此要么现用先转换,要么把它的数据复制到用户自己可以管理的内存中
const char *c;
string s = "1234";
c = s.c_str();
cout<<c<<endl;
s = "abcde";
cout<<c<<endl;
}
————————————————
输出结果:
1234
abcde
————————————————