在 C++11 中提供了专门的类型转换函数,可以非常方便地使用它们进行数值类型和字符串类型之间的转换。
数值转换为字符串
使用 to_string()
方法可以将各种数值类型转换为字符串类型,这是一个重载函函数声明位于头文件 <string>
中,函数原型如下:
1 2 3 4 5 6 7 8 9 10
| 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);
|
函数的使用是非常简单的,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <iostream> #include <string> using namespace std;
int main() { string pi = "pi is " + to_string(3.1415926); string love = "love is " + to_string(5.20 + 13.14); cout << pi << endl; cout << love << endl; return 0; }
|
字符串转换为数值
由于 C++ 中的数值类型包括整形和浮点型,对于不同的类型提供了不同的函数,通过调用这些函数可以将字符串类型转换为对应的数值类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 ); long stol( const std::string& str, std::size_t* pos = 0, int base = 10 ); long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long stoul( const std::string& str, std::size_t* pos = 0, int base = 10 ); unsigned long long stoull( const std::string& str, std::size_t* pos = 0, int base = 10 );
float stof( const std::string& str, std::size_t* pos = 0 ); double stod( const std::string& str, std::size_t* pos = 0 ); long double stold( const std::string& str, std::size_t* pos = 0 );
|
这些函数虽然都有多个参数,但是除去第一个参数外其他都有默认值,一般情况下使用默认值就能满足需求。函数的使用,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <iostream> #include <string> using namespace std;
int main() { string str1 = "45"; string str2 = "3.14159"; string str3 = "9527 with words"; string str4 = "words and 2";
int myint1 = std::stoi(str1); float myint2 = std::stof(str2); int myint3 = std::stoi(str3);
cout << "std::stoi(\"" << str1 << "\") is " << myint1 << endl; cout << "std::stof(\"" << str2 << "\") is " << myint2 << endl; cout << "std::stoi(\"" << str3 << "\") is " << myint3 << endl;
return 0; }
|
在 C++11 提供的这些转换函数将字符串转换为数值的过程中,可能的情况如下:
(1)如果字符串中所有字符都是数值类型,则整个字符串会被转换为对应的数值,并通过返回值返回
(2)如果字符串的前半部分字符是数值类型,后半部不是,则前半部分会被转换为对应的数值,并通过返回值返回
(3)如果字符第一个字符不是数值类型,则转换失败
参考资料
https://subingwen.cn/cpp/convert