C++中int和string的互相转换

这里学习哒~

一、用sstream类

1. int -> string

#include<iostream>
#include<sstream>      //需要引用的头文件
using namespace std;

int main(){
    int x = 1234;        //需要转换的数字
    stringstream sstr;
    string str;

    sstr<<x;
    str = sstr.str();    //转换后的字符串
    cout << str <<endl;
    return 0;
}

2. string -> int

#include<iostream>
#include<sstream>      //需要引用的头文件
using namespace std;

int main(){
    int x;
    string str = "4321";  //需要转换的字符串
    stringstream sstr(str);

    sstr >> x;            //转换后的数字
    cout << x << endl;
}

缺点:处理大量数据时候速度慢;stringstream不会主动释放内存。

二、用sprintf、sscanf函数

1. int -> string

#include<iostream>
using namespace std;

int main(){
    int x = 1234;    //需要转换的数字
    string str;
    char ch[5];      //需要定义的字符串数组:容量等于数字长度+1即可

    sprintf(ch,"%d", x);
    str = ch;         //转换后的字符串
    cout << str << endl;
}

2. string -> int、float

#include<iostream>
using namespace std;

int main(){
    char ch[10] = "12.34";    //需要转换的字符串
    int x;                    //转换后的int型
    float f;                  //转换后的float型

    sscanf(ch, "%d", &x);      //转换到int过程
    sscanf(ch, "%f", &f);      //转换到float过程

    cout << x << endl;
    cout << f << endl;
}

三、C标准库atoi, atof, atol, atoll(C++11标准) 函数

可以将字符串转换成int,double, long, long long 型

1. int -> string

itoa函数:
定义:
char *itoa(int value, char *string, int radix);
参数:
① value:需要转换的int型
② string:转换后的字符串,为字符串数组
③ radix:进制,范围2-36

(没run起来,一直报错,随后再补)

2. string -> int、double、long、long long

atoi函数:
定义:
int atoi(const char *nptr);
double atof(const char *nptr);
long atol(const char *nptr);
long long atoll(const char *nptr);
参数:
① nptr:字符串数组首地址

#include<iostream>
#include<stdlib.h>      //需要引用的头文件
using namespace std;

int main(){
    int x;
    char ch[] = "4321";    //需要转换的字符串
    x = atoi(ch);          //转换后的int数字

    cout << x << endl;
}

原文链接: https://www.cnblogs.com/doubleyue/p/15925425.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中int和string的互相转换

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/187974

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午1:54
下一篇 2023年2月12日 下午1:54

相关推荐