在写C++时经常会遇到字符串string与int等数字之间的相互转化,在java这种语言特性特别丰富的语言中能够通过Integer和String包装类中的函数parseInt和valueOf等函数轻松转换,而在C++中一直没有特别好的处理办法。
在之前的经历中,我都是通过C++中的字符串流stringstream来进行转换的,即通过如下函数:
1 int str2int(string input){ 2 stringstream ss; 3 ss<<input; 4 int res; 5 ss>>res; 6 return res; 7 }
以及:
1 string int2str(int input){ 2 stringstream ss; 3 ss<<input; 4 string res; 5 ss>>res; 6 return res; 7 }
但这样写的效率并不高,特别是遇到大批量这种转换需要进行的时候。
直到今天在网上进一步搜索的时候才发现C++11 增加的特性中string类已经增加了完整的处理方法:
std::to_string
string to_string (int val); string to_string (long val); string to_string (long long val); string to_string (unsigned val); string to_string (unsigned long val); string to_string (unsigned long long val); string to_string (float val); string to_string (double val); string to_string (long double val); to_string函数几乎可以将所有数字类型转换成string;而包括std::stod,std::stof等等函数可以轻松把string转换成各种数字类型,具体可见此处。
std::stoi
nt stoi (const string& str, size_t* idx = 0, int base = 10); int stoi (const wstring& str, size_t* idx = 0, int base = 10);
下面分析一下stoi函数中两个可选参数的意义:
Parameters
- str //第一个参数是需要转换成数字的string
- String object with the representation of an integral number.
- idx //第二个参数是一个指向size_t类型变量的指针,通过传入该参数可以获取在转换成数字之后的字符串起始位置,具体看后面的example
- Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used. - base //第三个参数表示string中数字的表现进制形式,常用的有二进制,十进制(默认),十六进制等。
- Numerical base (radix) that determines the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the sequence (see strtol for details). Notice that by default this argument is 10, not 0.
1 // stoi example 2 #include <iostream> // std::cout 3 #include <string> // std::string, std::stoi 4 5 int main () 6 { 7 std::string str_dec = "2001, A Space Odyssey"; 8 std::string str_hex = "40c3"; 9 std::string str_bin = "-10010110001"; 10 std::string str_auto = "0x7f"; 11 12 std::string::size_type sz; // alias of size_t 13 14 int i_dec = std::stoi (str_dec,&sz); //sz的指针作为参数传入函数,获取截断数字之后的开始位置 15 int i_hex = std::stoi (str_hex,nullptr,16); 16 int i_bin = std::stoi (str_bin,nullptr,2); 17 int i_auto = std::stoi (str_auto,nullptr,0); 18 19 std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n"; //substr从截断处开始截取 20 std::cout << str_hex << ": " << i_hex << ‘\n‘; 21 std::cout << str_bin << ": " << i_bin << ‘\n‘; 22 std::cout << str_auto << ": " << i_auto << ‘\n‘; 23 24 return 0; 25 }
Output:
2001, A Space Odyssey: 2001 and [, A Space Odyssey] 40c3: 16579 -10010110001: -1201 0x7f: 127 |
参考:
http://www.cplusplus.com/reference/string/stoi/
http://www.cplusplus.com/reference/string/to_string/
原文地址:https://www.cnblogs.com/J1ac/p/8229150.html
时间: 2024-10-13 11:44:21