1、string类
1.1 数值转换为string
1.1.1 使用函数模板
用ostringstream类构造格式化输出流,将要转换的基本数据类型数值传到流中
string toString(const T& t)
{
ostringstream dataToString;
dataToString << t;
return dataToString.str();
}
1.1.2 使用标准库函数std::to_string(), 注意包含头文件#include <string> ,以及使用命名空间std
example
// to_string example
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
参数类型有
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
int | "%d" | Decimal-base representation of val. The representations of negative values are preceded with a minus sign (-). |
long | "%ld | |
long long | "%lld | |
unsigned | "%u" | Decimal-base representation of val. |
unsigned long | "%lu | |
unsigned long long | "%llu | |
float | "%f" | As many digits are written as needed to represent the integral part, followed by the decimal-point character and six decimal digits. inf (or infinity) is used to represent infinity. nan (followed by an optional sequence of characters) to represent NaNs (Not-a-Number). The representations of negative values are preceded with a minus sign (-). |
double | "%f | |
long double | "%Lf |
1.2 string字符串转化为数值类型
string的stod、stof、stoi、stol、stold、stoll、stoul、stoull函数可以将string字符串转化为对应的类型
example
// stod example
#include <iostream> // std::cout
#include <string> // std::string, std::stod
int main ()
{
std::string orbits ("365.24 29.53");
std::string::size_type sz; // alias of size_t
double earth = std::stod (orbits,&sz);
double moon = std::stod (orbits.substr(sz));
std::cout << "The moon completes " << (earth/moon) << " orbits per Earth year.\n";
return 0;
}