字符串(string、char*) 與 數字(int) 相互轉換

一、string 轉換爲 數字(stoi)

string str = "010";
int a = stoi(str, 0, 10);  //目標字符串,起始位置,n進制
cout << a;   // output:10  //自動去除前導零
 
注意:此函數在 PTA 可以使用,而藍橋杯不允許

若要用可以使用代替的函數表示,舉例如下:

int stoi(string s)
{
	int len=s.size(),sum=0;
	for(int i=0;i<len;i++)
		sum=sum*10+(s[i]-'0');
	return sum;
}

二、char 型數組轉換爲 數字(atoi)

char s[] = "010";
int a = atoi(s);
cout << a;  // output:10  //自動去除前導零
 
注意:此函數在 PTA 可以使用,而藍橋杯不允許

若要用可以使用代替的函數表示,舉例如下:

int atoi(char s[])
{
	int len=strlen(s),sum=0;
	for(int i=0;i<len;i++)
		sum=sum*10+(s[i]-'0');
	return sum;
}

// 補充
string s1 = "010";
int a1 = atoi(s1.c_str()); // c_str()函數是將 string以 char*形式輸出 
cout << a1;   // output:10

三、數字 轉換爲 string(to_string)

int a = 10;
string s = to_string(a);
cout << a;  // output:10

注意:此函數在 PTA 可以使用,而藍橋杯不允許

若要用可以使用代替的函數表示,舉例如下:

string  to_string(int a)
{
	string b="";
	char c[1000]={0}; //存儲空間根據題目調整 
	sprintf(c,"%d",a);
	for(int i=0;i<strlen(c);i++)
		b+=c[i];
	return b;
}

四、數字 轉換爲 char 型數組(itoa、sprintf )

int a = 10;
char s[100]={0};
itoa(a,s,10);  //目標數字,存儲 char型數組,n進制
cout << s;  // output:10

注意:此函數在 PTA 可以使用,而藍橋杯不允許

可以用 sprintf 代替 itoa :

int a = 10;
char c[100]={0};
sprintf(c,"%d",a);  //將 a 格式化輸入到 c(字符串)中 (注意沒有&號)
cout << c;  // output:10
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章