您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。