在 C++ 中,std::to_string()
函数用于将数字类型(如 int、float、double 等)转换为字符串
#include<iostream>
#include<string>
int main() {
int num = 42;
std::string str_num = std::to_string(num);
std::cout << "The integer is: "<< num<< std::endl;
std::cout << "The string representation of the integer is: "<< str_num<< std::endl;
return 0;
}
输出结果:
The integer is: 42
The string representation of the integer is: 42
std::to_string()
函数还可以用于其他数字类型,例如 float 和 double:
#include<iostream>
#include<string>
int main() {
float num_float = 3.14f;
std::string str_num_float = std::to_string(num_float);
double num_double = 2.71828;
std::string str_num_double = std::to_string(num_double);
std::cout << "The float is: "<< num_float<< std::endl;
std::cout << "The string representation of the float is: "<< str_num_float<< std::endl;
std::cout << "The double is: "<< num_double<< std::endl;
std::cout << "The string representation of the double is: "<< str_num_double<< std::endl;
return 0;
}
输出结果:
The float is: 3.14
The string representation of the float is: 3.14
The double is: 2.71828
The string representation of the double is: 2.71828
请注意,对于浮点数,std::to_string()
的精度可能与预期不同。如果需要更高的精度或格式控制,可以考虑使用 std::ostringstream
或 C++ 标准库中的其他字符串格式化工具。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。