数值相互转换
在 C++ 里,std::string
与数值类型(如 int
、double
等)之间的转换是常见操作。下面详细介绍几种实现转换的方式。
1. 使用标准库函数进行转换
1.1 std::stoi
、std::stol
、std::stoll
等(字符串转整数)
这些函数用于将字符串转换为不同类型的整数,具体如下:
std::stoi
:将字符串转换为int
类型。std::stol
:将字符串转换为long
类型。std::stoll
:将字符串转换为long long
类型。
#include <iostream> #include <string> int main() { std::string str = "12345"; int num = std::stoi(str); std::cout << "转换后的整数: " << num << std::endl; return 0; }
1.2 std::stof
、std::stod
、std::stold
等(字符串转浮点数)
这些函数用于将字符串转换为不同类型的浮点数,具体如下:
std::stof
:将字符串转换为float
类型。std::stod
:将字符串转换为double
类型。std::stold
:将字符串转换为long double
类型。
#include <iostream> #include <string> int main() { std::string str = "3.14"; double num = std::stod(str); std::cout << "转换后的浮点数: " << num << std::endl; return 0; }
1.3 std::to_string
(数值转字符串)
std::to_string
函数可将各种数值类型(如 int
、double
等)转换为 std::string
类型。
#include <iostream> #include <string> int main() { int num = 123; std::string str = std::to_string(num); std::cout << "转换后的字符串: " << str << std::endl; double d = 3.14; std::string str_d = std::to_string(d); std::cout << "转换后的字符串: " << str_d << std::endl; return 0; }
2. 使用 stringstream
进行转换
2.1 字符串转数值
std::stringstream
是一个流类,可用于在字符串和其他数据类型之间进行转换。以下是将字符串转换为整数的示例:
#include <iostream> #include <sstream> #include <string> int main() { std::string str = "456"; int num; std::stringstream ss(str); ss >> num; if (!ss.fail()) { std::cout << "转换后的整数: " << num << std::endl; } return 0; }
2.2 数值转字符串
同样可以使用 std::stringstream
将数值转换为字符串。
#include <iostream> #include <sstream> #include <string> int main() { int num = 789; std::stringstream ss; ss << num; std::string str = ss.str(); std::cout << "转换后的字符串: " << str << std::endl; return 0; }
3. 旧的 C 风格转换函数(不推荐用于 C++ 新项目)
3.1 atoi
、atol
、atoll
(字符串转整数)
这些是 C 语言中的函数,在 C++ 中也可使用,但不推荐,因为它们没有错误处理机制。
#include <iostream> #include <cstdlib> #include <string> int main() { std::string str = "987"; int num = std::atoi(str.c_str()); std::cout << "转换后的整数: " << num << std::endl; return 0; }
3.2 sprintf
(数值转字符串)
sprintf
也是 C 语言中的函数,可将数值格式化输出到字符串中。
#include <iostream> #include <cstdio> #include <string> int main() { int num = 654; char buffer[20]; std::sprintf(buffer, "%d", num); std::string str(buffer); std::cout << "转换后的字符串: " << str << std::endl; return 0; }
综上所述,在 C++ 中推荐使用标准库函数(如 std::stoi
、std::to_string
)进行字符串和数值的转换,因为它们更安全、易用且符合 C++ 的风格。而 stringstream
则提供了更灵活的格式化转换能力。
考研机试常用的数据结构 文章被收录于专栏
考研机试常用的数据结构