將整形數轉換為字符串


題目

寫一個 IntToStr(int a); 函數將一個整形數轉換為字符串。

考點

此題有兩種解法,一種是自己編寫算法程序,另一種是通過字符串輸入輸出流中的函數

實現

自己編寫

#include<iostream>
#include<vector>
using namespace std;

const int MaxSize = 10000;

char* intToStr(int a) {			//要處理正負
	int n, temp = a;
	for (n = 0; temp != 0; n++)
		temp /= 10;
	char* ch = new char[MaxSize] ();
	if (a < 0) {
		ch[0] = '-';
		a *= -1;
		for (; n != 0; n--) {
			ch[n] = a % 10 + '0';			//注意后面這個加,將整數轉換成ASCII碼的關鍵所在
			a /= 10;
		}
	}
	else {
		for (; n != 0; n--) {
			ch[n - 1] = a % 10 + '0';
			a /= 10;
		}
	}
	return ch;
}

int main() {
	int a;
	cin >> a;
	char *ch = intToStr(a);
	cout << ch;
	delete []ch;
	return 0;
}

字符串流

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

string intToStr(int a) {               //整型到字符串
	ostringstream os;
	os << a;
	return os.str();                //str()函數
}

int strToInt(string str) {            //字符串到整型
	istringstream is(str);		//創建字符串輸入流並用str初始化
	int a;
	is >> a;			//可以實現自動轉換,將字符串輸入流輸入到a中
	return a;

}

int main() {
	int a;
	cin >> a;
	string str = intToStr(a);
	cout << str << endl;
	int b = strToInt(str);
	cout << b << endl;
	return 0;
}


免責聲明!

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



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