STL-string
一、简述
字符串,已经封装char,string内部存储着数据的指针。所以sizeof获取string大小时返回的不是数据实际大小。
二、常用功能
2.1数字转字符串
参考:
- https://www.cplusplus.com/reference/string/to_string/
- https://www.cplusplus.com/reference/iomanip/setprecision/
- https://www.cplusplus.com/reference/sstream/ostringstream/ostringstream/
2.1.1整数转字符串
1 int ci = 19; 2 std::string mystr, mystr2; 3 //mystr:字符串19 4 mystr = std::to_string(ci);
转指定长度字符串,长度不足自动前面补0:
1 int num= 99; //待转的数字 2 int width = 4; //指定的宽度 3 string num_str = to_string(num); 4 //判断转字符串后是不是满足设定位数,不足则补零 5 while(num_str.size() < width){ num_str = "0" + num_str;}
2.1.2浮点数转字符串
默认保存浮点数小数点后6位数字
指定保存精度方法:
需要标准库:
#include <sstream>
#include <iomanip>
1 //包含头文件 2 //#include <string> 3 //#include <iomanip> 4 //#include <sstream> 5 //********************************************* 6 float f = 3.1416926; 7 std::string sf; 8 std::ostringstream ss; 9 ss << std::setprecision(7) << f; 10 //sft:此时保留包括整数部分的7位有效数字3.141692 11 std::string sft = ss.str(); 12 ss.str(""); 13 //清空ss不能用clear 14 //clear作用:清空错误的标志位 15 //ss.clear(); 16 17 //设置小数部分有效位 18 ss << std::fixed; 19 ss << std::setprecision(7) << f; 20 //sf:此时保留小数7位有效数字3.1416926 21 sf = ss.str();
2.2字符串转数字
相关函数
1 //字符串转double 2 double stod (const string& str, size_t* idx = 0); 3 double stod (const wstring& str, size_t* idx = 0); 4 5 //转浮点型 6 float stof (const string& str, size_t* idx = 0); 7 float stof (const wstring& str, size_t* idx = 0); 8 9 //转int 10 int stoi (const string& str, size_t* idx = 0, int base = 10); 11 int stoi (const wstring& str, size_t* idx = 0, int base = 10); 12 13 //转long 14 long stol (const string& str, size_t* idx = 0, int base = 10); 15 long stol (const wstring& str, size_t* idx = 0, int base = 10); 16 17 long double stold (const string& str, size_t* idx = 0); 18 long double stold (const wstring& str, size_t* idx = 0); 19 20 long long stoll (const string& str, size_t* idx = 0, int base = 10); 21 long long stoll (const wstring& str, size_t* idx = 0, int base = 10); 22 23 unsigned long stoul (const string& str, size_t* idx = 0, int base = 10); 24 unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10); 25 26 27 unsigned long long stoull (const string& str, size_t* idx = 0, int base = 10); 28 unsigned long long stoull (const wstring& str, size_t* idx = 0, int base = 10); 29 30
三、相关参考
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。