在 C++ 中,std::to_string()
函数用于将基本数据类型(如 int、float、double 等)转换为字符串。以下是一些使用 std::to_string()
的示例和其他实现方法:
std::to_string()
直接转换整数:#include<iostream>
#include<string>
int main() {
int num = 42;
std::string str_num = std::to_string(num);
std::cout << "Number as string: "<< str_num<< std::endl;
return 0;
}
std::ostringstream
将整数转换为字符串:#include<iostream>
#include <sstream>
#include<string>
int main() {
int num = 42;
std::ostringstream oss;
oss<< num;
std::string str_num = oss.str();
std::cout << "Number as string: "<< str_num<< std::endl;
return 0;
}
std::snprintf()
将整数转换为字符串:#include<iostream>
#include <cstdio>
#include<string>
int main() {
int num = 42;
char buffer[20];
std::snprintf(buffer, sizeof(buffer), "%d", num);
std::string str_num(buffer);
std::cout << "Number as string: "<< str_num<< std::endl;
return 0;
}
boost::lexical_cast
将整数转换为字符串(需要包含 Boost 库):#include<iostream>
#include<boost/lexical_cast.hpp>
int main() {
int num = 42;
std::string str_num = boost::lexical_cast<std::string>(num);
std::cout << "Number as string: "<< str_num<< std::endl;
return 0;
}
这些示例展示了将整数转换为字符串的不同方法。你可以根据项目需求和编译器支持选择合适的方法。对于现代 C++ 编译器,建议使用 std::to_string()
,因为它简单且性能良好。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。