一、使用stringstream
#include <iostream> #include <sstream> using namespace std; int main() { double num = 3.141592653589793238; stringstream ss; ss << num; string str = ss.str(); cout << str << endl; return 0; }
對於C++ Double類型的轉換,可以使用stringstream進行處理。通過將Double類型的數值插入到stringstream中,再轉化為字符串的形式,最終輸出。
二、使用to_string函數
#include <iostream> #include <string> using namespace std; int main() { double num = 3.141592653589793238; string str = to_string(num); cout << str << endl; return 0; }
除了stringstream,我們還可以使用C++11中提供的to_string函數,直接將Double類型的數值轉化為字符串。代碼也更加簡潔明了。
三、使用sprintf函數
#include <iostream> #include <cstdio> using namespace std; int main() { double num = 3.141592653589793238; char buffer[20]; sprintf(buffer, "%lf", num); string str = buffer; cout << str << endl; return 0; }
還有一種方法是使用C/C++中常用的sprintf函數。該函數可以將給定的Double類型數值格式化為字符串,並存儲在指定的字符數組中。再將該字符數組轉化為字符串,最終輸出。
總結
以上三種方法都可以將C++ Double類型轉換為字符串,每種方法有各自的優劣,需要根據具體情況選擇適合自己的方法進行處理。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/231982.html