• 关于C++中string对象向int、float、double类型的转换的方法汇总


    一、利用stringstream对象

    stringstream在int或float类型转换为string类型的方法中已经介绍过, 这里也能用作将string类型转换为常用的数值类型。

    #include <iostream>
    #include <sstream>    //使用stringstream需要引入这个头文件
    using namespace std;
    
    //模板函数:将string类型变量转换为常用的数值类型(此方法具有普遍适用性)
    template <class Type>
    Type stringToNum(const string& str)
    {
        istringstream iss(str);
        Type num;
        iss >> num;
        return num;    
    }
    
    int main(int argc, char* argv[])
    {
        string str("00801");
        cout << stringToNum<int>(str) << endl;
    
        system("pause");
        return 0;
    }

    二、使用atoi()、 atil() 、atof()函数  -----------------实际上是char类型向数值类型的转换

    注意:使用 atoi 的话,如果 string s 为空,返回值为0.则无法判断s是0还是空

    1. atoi():      int atoi ( const char * str );

    说明:Parses the C string str interpreting its content as an integral number, which is returned as an int value.

    参数:str : C string beginning with the representation of an integral number.

    返回值:1. 成功转换显示一个Int类型的值.  2. 不可转换的字符串返回0.  3.如果转换后缓冲区溢出,返回 INT_MAXor INT_MIN

    /* atof example: sine calculator */
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    int main ()
    {
      double n,m;
      double pi=3.1415926535;
      char szInput [256];
      printf ( "Enter degrees: " );
      gets ( szInput );
      //char类型转换为double类型 
      n = atof ( szInput );
      m = sin (n*pi/180);
      printf ( "The sine of %f degrees is %f\n" , n, m );
      
      return 0;
    }
    2.aotl():  long int atol ( const char * str );

    说明:C string str interpreting its content as an integral number, which is returned as a long int value(用法和atoi函数类似,返回值为long int)

    3.atof():  double atof ( const char * str );

    参数:C string beginning with the representation of a floating-point number.

    返回值:1. 转换成功返回doublel类型的值 2.不能转换,返回0.0。  3.越界,返回HUGE_VAL

    /* atof example: sine calculator */
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    int main ()
    {
      double n,m;
      double pi=3.1415926535;
      char szInput [256];
      printf ( "Enter degrees: " );
      gets ( szInput );
      //char类型转换为double类型 
      n = atof ( szInput );
      m = sin (n*pi/180);
      printf ( "The sine of %f degrees is %f\n" , n, m );
      
      return 0;
    }
  • 相关阅读:
    [Vue] Computed property "XXX" was assigned to but it has no setter.
    vue路由传参的三种基本方式
    ECharts大屏数据可视化展板项目 适配rem
    vue-cli3.0结合lib-flexible、px2rem实现适配,完美解决第三方ui库样式变小问题
    element-ui 实现行合并-亲测有效!
    ui自动化用Tesseract类截取和识别验证码【多测师】
    史上最全软件测试工程师常见的面试题总结(一)【多测师】
    Python操作非关系型数据库Redis【多测师】
    Java当中的重载和重写的区别【多测师】
    3道经典的Python练习题【多测师】
  • 原文地址:https://www.cnblogs.com/jiabei521/p/3119028.html
Copyright © 2020-2023  润新知