代码成就万世基积沙镇海,梦想永在凌云意意气风发|

又一岁荣枯

园龄:3年4个月粉丝:11关注:6

c++ 数字与字符串的相互转换

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. 方法二(利用<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.字符串转换为数字

  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;
}
  1. 方法二(利用<string>中的stoi()函数,其中还有对于其他类型的函数,如stod(),stof()等,根据类型选取)
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int x;
    string str;
    cin >> str;
    x = stoi(str);
    cout << x;
    return 0;
}

本文作者:又一岁荣枯

本文链接:https://www.cnblogs.com/java-six/p/16097560.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   又一岁荣枯  阅读(1033)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起