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