zoukankan      html  css  js  c++  java
  • C++_数字字符串互相转换

    数字转换为字符串

    法一、利用<sstream>中的stringstream(字符串流)

     1 int main(){
     2 
     3     int x;
     4     string res;
     5     stringstream ss;
     6     cin>>x; ss<<x; ss>>res;
     7     cout<<res<<endl;
     8 
     9     return 0;
    10 }

    法二、利用<sstream>中的to_string,最好用于int,浮点数有些特殊

     1 int main(){
     2 
     3     double x;
     4     string res;
     5     stringstream ss;
     6     cin>>x; 
     7     res = to_string(x);
     8     cout<<res<<endl;
     9 
    10     return 0;
    11 }

    输出

    123.123
    123.123000

    浮点数会保存小数点后六位,不足补零。

    将字符串转为数字

    法一、利用<string>中的 stoi()、stof()、stod()函数,可将字符串分别转换为整型、单精度浮点型、双精度浮点型

    1 int main(){
    2 
    3     string res = "123";
    4     int x = stoi(res);
    5     cout<<x<<endl;
    6     return 0;
    7 }

    法二、利用<sstream>中的stringstream(字符串流)

    当然上面两种抓换也可通过sprintf、sscanf实现

  • 相关阅读:
    测试的种类
    软件测试的原则
    软件测试的目的
    软件测试的对象
    软件的分类
    软件测试
    mysql 视图
    mysql 字段添加以及删除
    mysql 引擎类型
    mysql 数据插入insert
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14332353.html
Copyright © 2011-2022 走看看