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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM