C++ string的万能转换,从long string 之间的转换来看看

  • Post author:
  • Post category:其他


本博客转自:

https://blog.csdn.net/vic___/article/details/9324897

string 转 long

那必须是万年atoi(),不过得配合c_str()使用!

#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main ()
{
    string a = "1234567890";
    long b = atoi(a.c_str());
    cout<<b<<endl;
    return 0;
}
long stol(string str)
{
    long result;
    istringstream is(str);
    is >> result;
    return result;
}

long 转 string

string ltos(long l)
{
    ostringstream os;
    os<<l;
    string result;
    istringstream is(os.str());
    is>>result;
    return result;
}

string 转float

float stof(string str)  
{  
    float result;  
    istringstream is(str);  
    is >> result;  
    return result;  
}