将整形数转换为字符串


题目

写一个 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