char [ ] 轉 int

範例一:
char x[ ]="258";
int a;
sscanf( x ,"%d" , &a);

範例二:(此例不一定每一個 compiler 都可以)
char x[ ]="258";
int a;
a = atoi(x);

範例三:(不使用轉型函數)
char x[ ]="1947";
int a, i, v;
a = 0;
v = 1;
for(i=strlen(x)-1; i>=0; i--){
    a += (x[i] - '0') * v;
    v *= 10;
}

string 轉 int

範例一:
#include<sstream>
string x = "1947";
istringstream y(x);
int a;
y >> a;
cout << a << endl;

範例二:
#include<sstream>
string x = "328";
int a;
stringstream y;
y << x;
y >> a;
cout << a << endl;

範例三:
#include<cstdlib>
string x = "179";
cout << atoi(x.c_str()) << endl;
//atoi 應傳入 char [ ],可使用string 的 c_str() 轉換。

範例四:(不使用轉型函數)
string x="498";
int a, i, v;
v=1;
a=0;
for(i=x.length()-1; i>=0;i--){
     a += (x[i]-'0')*v;
     v *= 10;
}
cout << a << endl;



int 轉 char [ ]

範例一:
#include <iostream> 或是 #include <stdio.h>
char x[100];
int a = 257;
sprintf( x , "%d", a ); //int 轉 char [ ]
cout << x << endl;

範例二:(此例不一定每一個 compiler 都可以)
#include <iostream> 或是 #include <stdlib.h>
char x[100];
int a = 257;
itoa(a,x,10); //將 int 以 10 進制轉成字串放到 x
cout << x << endl;

範例三:(不使用轉型函數)
char x[100], k;
int a = 4258, i, u;
for(i=0; a>0; i++){
     x[i] = (a % 10) + '0';
     a /= 10;
}
x[i] = '\0';//字串結尾
u = i; //字串長度
a = i/2;
for(i=0; i<a; i++){//字串必須反向
     k = x[i];
     x[i] = x[u-i-1];
     x[u-i-1] = k;
}
cout << x << endl;

int 轉 string

範例一:
#include<sstream>
string x="";
ostringstream y;
int a=518;
y << a;
x = y.str();
cout << x << endl;

範例二:
#include<sstream>
string x="";
int a=518;
stringstream y;
y << a;
y >> x;
cout << x << endl;

範例三:
string x="", y="";
int a = 258, b;
for(; a>0;){
     y = (char) ( (a % 10) + '0' );
     x = y + x;
     a /= 10;
}
cout << x << endl;