您好,登錄后才能下訂單哦!
std::to_string
是 C++11 標(biāo)準(zhǔn)庫中的一個函數(shù),用于將數(shù)字類型(如 int、float、double 等)轉(zhuǎn)換為字符串。以下是 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
和其他相關(guān)函數(shù)的多樣用法。你可以根據(jù)需要調(diào)整代碼以適應(yīng)不同的場景。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。