C++ 各种基本类型间的转换

常用的转换方法:

  1. 流转换
  2. STL标准函数库中函数转换

流转换

流转换主要是用到了<sstream>库中的stringstream类。

通过stringstream可以完成基本类型间的转换,

 1 #include<sstream>
 2 
 3 using namespace std;
 4 
 5 template<typename out_type, typename in_value>
 6 
 7 out_type convert(const in_value & t){
 8 
 9     stringstream stream;
10 
11     stream << t;
12 
13     out_type result;
14 
15     stream >> result;
16 
17     return result;
18 
19 }

STL函数转换

标准函数库里包含了基本类型间转换的函数,在库<stdlib.h>中。

基本的函数:

itoa():将整型值转换为字符串。

ltoa():将长整型值转换为字符串。

ultoa():将无符号长整型值转换为字符串。

gcvt():将浮点型数转换为字符串,取四舍五入。

ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。

fcvt():指定位数为转换精度,其余同ecvt()。

atof():将字符串转换为双精度浮点型值。

atoi():将字符串转换为整型值。

atol():将字符串转换为长整型值。

strtod():将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字。

strtol():将字符串转换为长整值,并报告不能被转换的所有剩余数字。

strtoul():将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字。

每个函数的参数不尽相同,比如

char* itoa(int value, char* string, int radix)

含义:将整数value转换成字符串存入string, radix为转换时所用基数(保存到字符串中的数据的进制基数 2 8 10 16)

int atoi(const char* nptr)

含义:跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。

如此看来,这种方法就没有流转换灵活,方便。

实例:

(使用流转换)

#include <iostream>
#include <sstream>

using namespace std;

template<typename out_type, typename in_value>
out_type convert(const in_value & t){
    stringstream stream;
    stream << t;
    out_type result;
    stream >> result;
    return result;
}

int main()
{
    char xxx[10] = "45126";
    int i = 45641;
    i = convert<int>(xxx);//字符串转换为整型
    cout << i;
}

结果:

(使用STL函数)

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    int i = 1254876;
    char x[10];
    itoa(i, x, 10);
    cout << x << endl;

    int n;
    char* y = "45128";
    n = atoi(y);
    cout << n << endl;
}

结果:

原文地址:https://www.cnblogs.com/StrayWolf/p/6082828.html