一、c++ to_string保留小數點後六位
使用to_string函數可以將數字轉換為字元串。默認情況下,to_string默認輸出6位小數,但這不一定是您想要的。C ++ 11引入了std :: to_string的另一個重載版本,該版本接受一個小數位數參數。
#include
#include
using namespace std;
int main() {
double num = 12.3456789;
string str1 = to_string(num);
string str2 = to_string(num).substr(0, 9);
string str3 = to_string(num).substr(0, to_string(num).find(".", 0)+7);
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
cout << "str3: " << str3 << endl;
return 0;
}
可以看到,str2僅保留小數點後的前九位,而str3將小數點後的數字截取到第七位。
二、c++ to_string補位
to_string不會在數字前面添加前導零。如果您需要添加前導零以使數字看起來更整齊,則可以使用其他一些方法:
#include
#include
#include
using namespace std;
int main() {
//方法一:使用iomanip setfill和setw操作
int num1 = 123;
stringstream ss;
ss << setw(8) << setfill('0') << num1;
cout << ss.str() << endl;
//方法二:使用sprintf函數
int num2 = 456;
char buf[10];
sprintf(buf, "%08d", num2);
cout << buf << endl;
return 0;
}
三、string函數作用
使用to_string返回的結果是一個字元串,它也可以使用C ++ STL中的標準string函數進行處理。
#include
#include
using namespace std;
int main() {
double num = 123.456789;
string str1 = to_string(num);
string str2 = "Hello World";
cout << str1.substr(0, 5) << endl; //截取前五個字元
cout << str2.size() << endl; //獲取字元串長度
return 0;
}
四、c++ to_string函數
to_string是C ++ 11中的標準庫函數,它將數字轉換為字元串,並可以接受任何數字類型。
#include
#include
using namespace std;
int main() {
int num1 = 123;
long num2 = 456789;
float num3 = 3.14f;
double num4 = 2.7182818;
string str1 = to_string(num1);
string str2 = to_string(num2);
string str3 = to_string(num3);
string str4 = to_string(num4);
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
cout << str4 << endl;
return 0;
}
五、c++ to_string 限定長度
使用to_string函數轉換數字時,如果超出字元串的最大長度,將自動截斷。為了確保輸出的字元串不會太長,可以使用std :: to_chars,該函數可以指定輸出的最大長度。
#include
#include
using namespace std;
int main() {
int num = 123456;
char buffer[10];
auto [p, ec] = to_chars(buffer, buffer + 10, num);
cout.write(buffer, p - buffer) << endl; //最大輸出10個字元
return 0;
}
六、c++ to_string 頭文件
to_string函數定義在頭文件,因此在使用to_string函數之前需要包含此頭文件。
#include
#include
using namespace std;
int main() {
double num = 3.14159;
string str = to_string(num);
cout << str << endl;
return 0;
}
七、c++ to_string函數作用
to_string函數的主要作用是將數字轉換為字元串。
八、c++ to_string列印二進位數
to_string還允許指定輸出數字的格式,例如二進位。下面的示例顯示如何使用to_string將數字轉換為二進位字元串。
#include
#include
#include
using namespace std;
int main() {
int num = 123;
string str = bitset(num).to_string();
cout << str << endl; //輸出二進位數
return 0;
}
九、c++ to_string為空
使用to_string函數轉換空指針時,將引發std ::bad_alloc異常。
#include
#include
using namespace std;
int main() {
int *ptr = nullptr;
try {
string str = to_string(*ptr);
}
catch (const std::exception &e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/296112.html
微信掃一掃
支付寶掃一掃