std::to_string
是 C++11 标准库中的一个函数,用于将数字类型(如 int、float、double 等)转换为字符串。以下是 std::to_string
的一些常见用法:
#include<iostream>
#include<string>
int main() {
int num = 42;
std::string str_num = std::to_string(num);
std::cout << "Integer: "<< num << ", String: "<< str_num<< std::endl;
return 0;
}
#include<iostream>
#include<string>
int main() {
double num = 3.14159;
std::string str_num = std::to_string(num);
std::cout << "Double: "<< num << ", String: "<< str_num<< std::endl;
return 0;
}
#include<iostream>
#include <iomanip>
#include <sstream>
#include<string>
std::string to_string_with_precision(const double value, const int precision) {
std::ostringstream out;
out<< std::fixed<< std::setprecision(precision)<< value;
return out.str();
}
int main() {
double num = 3.14159;
int precision = 2;
std::string str_num = to_string_with_precision(num, precision);
std::cout << "Double: "<< num << ", String (precision "<< precision << "): "<< str_num<< std::endl;
return 0;
}
#include<iostream>
#include <iomanip>
#include <sstream>
#include<string>
std::string to_scientific_string(const double value, const int precision) {
std::ostringstream out;
out<< std::scientific<< std::setprecision(precision)<< value;
return out.str();
}
int main() {
double num = 3.14159;
int precision = 2;
std::string str_num = to_scientific_string(num, precision);
std::cout << "Double: "<< num << ", Scientific String (precision "<< precision << "): "<< str_num<< std::endl;
return 0;
}
这些示例展示了 std::to_string
和其他相关函数的多样用法。你可以根据需要调整代码以适应不同的场景。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。