數字和字符串的相互轉換

1.C語言實現

1.1整數轉換爲字符串

sprintf(str,"%d",n) :把n以%d的格式傳輸給str(從右往左)

#include<cstdio>

int main() {
	char str[100];
	int n = 100;
	sprintf_s(str, "%d", n + 100);		//str = "200"
	printf_s("%s", str);
	return 0;
}

 

1.2字符串轉化爲整數

sscanf(str,"%d",&n):把字符串str以%d的格式傳輸個變量n(從左往右)

#include<cstdio>

int main() {
	char str[] = "123";
	int n;
	sscanf_s(str, "%d",&n);		//n = 123
	printf_s("%d", n+100);		//輸出223
	return 0;
}

 

2.C++實現(string類)

2.1整數轉換爲字符串

to_string()函數:注意僅c++11可以用,部分OJ無法編譯

#include<cstdio>
#include<iostream>
#include<string>
using namespace std;

int main() {
	int num = 100;
	string str = to_string(num);
	cout << str;
	return 0;
}

 

2.2字符串轉化爲整數

stoi() 函數

#include<cstdio>
#include<iostream>
#include<string>
using namespace std;

int main() {
	
	//string字符串
	string cc = "123";
	int dd = stoi(cc);    //只有stoi可以
	cout << dd << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章