一、整数与字符串的转换

1. 整数转字符串

  • 方法:使用 std::to_string(C++11 及以上支持)
    直接将整数类型(intlonglong long 等)转换为 std::string
    #include <string>
    #include <iostream>
    using namespace std;

    int main() {
    int num = 123;
    string s = to_string(num); // s = "123"
    cout << s << endl;
    return 0;
    }

2. 字符串转整数

  • 方法1:使用 std::stoistd::stolstd::stoll(C++11 及以上支持)
    分别用于转换为 intlonglong long,若字符串无法转换或超出范围,会抛出异常。
    #include <string>
    #include <iostream>
    using namespace std;

    int main() {
    string s = "789";
    int num = stoi(s); // num = 789
    cout << num << endl;
    return 0;
    }

二、浮点数与字符串的转换

1. 浮点数转字符串

  • 方法1:使用 std::to_string
    支持 floatdouble 等类型。
    #include <string>
    #include <iostream>
    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::stofstd::stodstd::stold(C++11 及以上支持)
    分别用于转换为 floatdoublelong double
    #include <string>
    #include <iostream>
    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_stringstoi/stod 系列函数简洁高效,stringstream 则更灵活(支持格式化、多类型拼接等)。