C++ 字符串与数字的转换
一、整数与字符串的转换
1. 整数转字符串
- 方法:使用
std::to_string(C++11 及以上支持)
直接将整数类型(int、long、long long等)转换为std::string。
using namespace std;
int main() {
int num = 123;
string s = to_string(num); // s = "123"
cout << s << endl;
return 0;
}
2. 字符串转整数
- 方法1:使用
std::stoi、std::stol、std::stoll(C++11 及以上支持)
分别用于转换为int、long、long long,若字符串无法转换或超出范围,会抛出异常。
using namespace std;
int main() {
string s = "789";
int num = stoi(s); // num = 789
cout << num << endl;
return 0;
}
二、浮点数与字符串的转换
1. 浮点数转字符串
- 方法1:使用
std::to_string
支持float、double等类型。
using namespace std;
int main() {
double d = 3.14159;
string s = to_string(d); // s = "3.141590"(默认保留6位小数)
cout << s << endl;
return 0;
}
2. 字符串转浮点数
- 方法1:使用
std::stof、std::stod、std::stold(C++11 及以上支持)
分别用于转换为float、double、long double。
using namespace std;
int main() {
string s = "2.718";
double d = stod(s); // d = 2.718
cout << d << endl;
return 0;
}
总结
| 转换方向 | 推荐方法(简单场景) | 推荐方法(复杂/格式化场景) |
|---|---|---|
| 整数 → 字符串 | std::to_string |
stringstream |
| 字符串 → 整数 | std::stoi/std::stol |
stringstream |
| 浮点数 → 字符串 | std::to_string |
stringstream + setprecision |
| 字符串 → 浮点数 | std::stof/std::stod |
stringstream |
根据场景选择即可,to_string 和 stoi/stod 系列函数简洁高效,stringstream 则更灵活(支持格式化、多类型拼接等)。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 宇宙尽头的森林!