string 与 int double 的转化

时间:2022-11-21 16:05:35
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    //string -> int float double
    string str = "088.123";
    cout << "string -> int float double" << endl;
    cout << atoi(str.c_str()) << endl;
    cout << atol(str.c_str()) << endl;
    cout << atof(str.c_str()) << endl;
    int a;
    float b;
    double c;
    istringstream iss(str);
    iss >> a >> b >> c;
    cout << a << " " << b << " " << c << endl;

    //int double float -> string
    a = 10;
    b = 10.123;
    c = 100.234;
    cout << "int double float -> string" << endl;
    cout << to_string(a) << " " << to_string(b) << " " << to_string(c) << endl;
    stringstream ss;
    ss << a << " " << b << " " << c;
    cout << ss.str() << endl;

    return 0;
}