字符串与数字相互转换

1.数字to字符串

1.1、方法一(利用<sstream>的stringstream,可以是浮点数)

 

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    double x;
    string str;
    stringstream ss;
    cin>>x;
    ss<<x;
    ss>>str;
    cout<<str;
    return 0;
}

1.2、方法二(利用<sstream>中的to_string方法,浮点数会附带小数点后六位,不足补零,不推荐浮点数使用)

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    double x;
    string str;
    cin>>x;
    str=to_string(x);
    cout<<str;
    return 0;
}

 

2.字符串to数字

 

2.1、方法一(利用<sstream>的stringstream,可以是浮点数)

 

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    double x;
    string str;
    stringstream ss;
    cin>>str;
    ss<<str;
    ss>>x;
    cout<<x;
    return 0;
}

 

 

2.2、方法二(利用<string>中的stoi()函数,其中还有对于其他类型的函数,如stod(),stof()等,根据类型选取)

//如果遇到非法输入,stoi会自动截取最前面的数字,直到遇到不是数字为止
#include <iostream>
#include <string>
using namespace std;
int main()
{
    int x;
    string str;
    cin>>str;
    x=stoi(str);
    cout<<x;
    return 0;
}

 

 

2.3、从前往后逐个变换

int a=0;
for(int i=0;i<strlen(chr);i++)
{
        a=a*10+(chr[i]-'0');
}

 

2.4、从后往前使用pow逐个变换

#include <cmath>
int count=0,a=0;
for(int i=strlen(chr);i>=0;i--)
{
        a+=pow(10,count++)*(chr[i]-'0');  
}

 

2.5、【string字符串转double/int】stod函数

#include <iostream>
#include <string>
using namespace std;
int main()
{
    double x;
    string str;

    cin>>str;
    x=stod(str);
    cout<<x;
    return 0;
}

 

2.6、附【stoi和atoi区别】

stoi的形参是const string*,而atoi的形参是const char*。c_str()的作用是将const string*转化为const char*。  

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int x,y,z;
    string str;
    char chr[100];
    cin>>str;
    cin>>chr;
    x=stoi(str);
    y=atoi(chr);
    z=atoi(str.c_str());
    cout<<x<<endl;
    cout<<y<<endl;
    cout<<z<<endl;
    return 0;
}

  

  

  

 

posted @ 2021-02-03 22:29  yyer  阅读(694)  评论(0)    收藏  举报