【C++奇迹之旅】:字符串转换成数字将数字转换成字符串大全
加粗样式

文章目录
- 📝字符串转换成数字
- 1. 使用标准库函数
- 转换为整数
- 转换为浮点数
- 2. 使用 `std::strtol`、`std::strtod` 等 C 风格函数
- 3. 使用 `std::stringstream`
- 🌉将数字转换成字符串
- 1. 使用 `std::to_string` 函数
- 2. 使用 `std::stringstream`
- 3. 使用 C 风格的函数(如 `sprintf` 或 `snprintf`)
- 4. 使用 `std::format`(C++20 及以后)
- 🚩总结
📝字符串转换成数字
在 C++ 里,把字符串转换成数字有多种方式,下面针对不同的数据类型和使用场景详细介绍具体
1. 使用标准库函数
转换为整数
可以使用 std::stoi(转换为 int 类型)、std::stol(转换为 long 类型)、std::stoll(转换为 long long 类型)等函数。这些函数定义在 <string> 头文件中。
#include <iostream>
#include <string>
int main() {
std::string strInt = "12345";
try {
int numInt = std::stoi(strInt);
std::cout << "Converted to int: " << numInt << std::endl;
long numLong = std::stol(strInt);
std::cout << "Converted to long: " << numLong << std::endl;
long long numLongLong = std::stoll(strInt);
std::cout << "Converted to long long: " << numLongLong << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "Invalid argument: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "Out of range: " << e.what() << std::endl;
}
return 0;
}
解释:
std::stoi、std::stol、std::stoll函数会尝试将字符串转换为对应的整数类型。- 如果字符串不能正确转换为数字,会抛出
std::invalid_argument异常;如果转换后的数字超出了目标类型的范围,会抛出std::out_of_range异常。
转换为浮点数
可以使用 std::stof(转换为 float 类型)、std::stod(转换为 double 类型)、std::stold(转换为 long double 类型)等函数。
#include <iostream>
#include <string>
int main() {
std::string strFloat = "3.14159";
try {
float numFloat = std::stof(strFloat);
std::cout << "Converted to float: " << numFloat << std::endl;
double numDouble = std::stod(strFloat);
std::cout << "Converted to double: " << numDouble << std::endl;
long double numLongDouble = std::stold(strFloat);
std::cout << "Converted to long double: " << numLongDouble << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "Invalid argument: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "Out of range: " << e.what() << std::endl;
}
return 0;
}
解释:
std::stof、std::stod、std::stold函数用于将字符串转换为对应的浮点数类型。- 同样,若字符串无法正确转换,会抛出
std::invalid_argument异常;若结果超出范围,会抛出std::out_of_range异常。
2. 使用 std::strtol、std::strtod 等 C 风格函数
这些函数定义在 <cstdlib> 头文件中,是 C 语言遗留下来的函数,在 C++ 中也可以使用。
#include <iostream>
#include <cstdlib>
int main() {
const char* strInt = "23456";
char* endptr;
long numLong = std::strtol(strInt, &endptr, 10);
if (*endptr == '\0') {
std::cout << "Converted to long using strtol: " << numLong << std::endl;
} else {
std::cout << "Conversion error: not a valid number." << std::endl;
}
const char* strFloat = "2.71828";
double numDouble = std::strtod(strFloat, &endptr);
if (*endptr == '\0') {
std::cout << "Converted to double using strtod: " << numDouble << std::endl;
} else {
std::cout << "Conversion error: not a valid number." << std::endl;
}
return 0;
}
解释:
std::strtol用于将字符串转换为long类型,std::strtod用于将字符串转换为double类型。endptr是一个指向字符的指针,函数会将其设置为字符串中第一个无法转换为数字的字符的位置。如果*endptr是字符串结束符'\0',则表示整个字符串都被成功转换。
3. 使用 std::stringstream
std::stringstream 定义在 <sstream> 头文件中,可以实现字符串和各种数据类型之间的转换。
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string str = "456";
int num;
std::stringstream ss(str);
if (ss >> num) {
std::cout << "Converted to int using stringstream: " << num << std::endl;
} else {
std::cout << "Conversion error using stringstream." << std::endl;
}
std::string strFloat = "5.67";
double numDouble;
std::stringstream ssFloat(strFloat);
if (ssFloat >> numDouble) {
std::cout << "Converted to double using stringstream: " << numDouble << std::endl;
} else {
std::cout << "Conversion error using stringstream." << std::endl;
}
return 0;
}
解释:
- 首先创建一个
std::stringstream对象,并将字符串传递给它。 - 然后使用
>>运算符将字符串流中的内容提取到目标变量中。如果提取成功,>>运算符返回true;否则返回false。
综上所述,在 C++ 中可以根据具体需求和场景选择合适的方法将字符串转换为数字。通常情况下,使用标准库函数(如 std::stoi、std::stod 等)是比较简洁和安全的方式。
🌉将数字转换成字符串
1. 使用 std::to_string 函数
std::to_string 是 C++11 引入的标准库函数,它可以将整数(如 int、long、long long 等)和浮点数(如 float、double、long double 等)转换为 std::string 类型。该函数定义在 <string> 头文件中。
#include <iostream>
#include <string>
int main() {
// 整数转换
int numInt = 123;
std::string strInt = std::to_string(numInt);
std::cout << "Integer converted to string: " << strInt << std::endl;
// 浮点数转换
double numDouble = 3.14;
std::string strDouble = std::to_string(numDouble);
std::cout << "Double converted to string: " << strDouble << std::endl;
return 0;
}
解释:
std::to_string函数会根据传入的数字类型自动处理转换,使用起来非常方便。- 对于浮点数,转换后的字符串会包含一定的小数位数,具体位数可能因编译器和系统而异。
2. 使用 std::stringstream
std::stringstream 是 C++ 标准库中的流类,定义在 <sstream> 头文件中,可用于在字符串和各种数据类型之间进行转换。
#include <iostream>
#include <sstream>
#include <string>
int main() {
// 整数转换
int numInt = 456;
std::stringstream ssInt;
ssInt << numInt;
std::string strInt = ssInt.str();
std::cout << "Integer converted to string using stringstream: " << strInt << std::endl;
// 浮点数转换
double numDouble = 2.718;
std::stringstream ssDouble;
ssDouble << numDouble;
std::string strDouble = ssDouble.str();
std::cout << "Double converted to string using stringstream: " << strDouble << std::endl;
return 0;
}
解释:
- 首先创建一个
std::stringstream对象。 - 使用
<<运算符将数字插入到stringstream中。 - 最后调用
str()方法获取stringstream中的字符串内容。
3. 使用 C 风格的函数(如 sprintf 或 snprintf)
sprintf 和 snprintf 是 C 语言中的格式化输出函数,在 C++ 中也可以使用。它们定义在 <cstdio> 头文件中。
#include <iostream>
#include <cstdio>
#include <string>
int main() {
// 整数转换
int numInt = 789;
char bufferInt[20];
std::sprintf(bufferInt, "%d", numInt);
std::string strInt(bufferInt);
std::cout << "Integer converted to string using sprintf: " << strInt << std::endl;
// 浮点数转换
double numDouble = 1.618;
char bufferDouble[20];
std::sprintf(bufferDouble, "%f", numDouble);
std::string strDouble(bufferDouble);
std::cout << "Double converted to string using sprintf: " << strDouble << std::endl;
return 0;
}
解释:
sprintf函数将数字按照指定的格式(如%d表示整数,%f表示浮点数)写入到字符数组中。- 然后使用字符数组构造
std::string对象。
4. 使用 std::format(C++20 及以后)
std::format 是 C++20 引入的格式化字符串函数,它提供了一种简洁且类型安全的方式来进行字符串格式化,包括数字到字符串的转换。该函数定义在 <format> 头文件中。
#include <iostream>
#include <format>
int main() {
// 整数转换
int numInt = 999;
std::string strInt = std::format("{}", numInt);
std::cout << "Integer converted to string using std::format: " << strInt << std::endl;
// 浮点数转换
double numDouble = 0.577;
std::string strDouble = std::format("{}", numDouble);
std::cout << "Double converted to string using std::format: " << strDouble << std::endl;
return 0;
}
解释:
std::format函数使用占位符{}来表示要插入的值,会自动将数字转换为字符串并插入到指定位置。- 这种方式代码简洁,且类型安全,避免了一些传统格式化函数可能出现的错误。
🚩总结

