数字与字符串:倒序和相互转换

//源代码已在VS2010编译通过
#include 
#include 
#include 
#include 
using namespace std;

int NumReverse(int n)
{
	int t = 0;
	while(n > 0)
	{
		t = 10 * t + n % 10;
		n /= 10;
	}
	return t;
}

string StrReverse(string str)
{
	string s(str.rbegin(), str.rend());
	return s;
}

string Num2Str(int n)
{
	stringstream stream;
	string s;
	stream << n;
	stream >> s;
	return s;
}

int Str2Num(string str)
{
	stringstream stream;
	int t;
	stream << str;
	stream >> t;
	return t;
}

int main()
{
	//数字倒序
	int n1, n2;
	n1 = 12345678;
	n2 = NumReverse(n1);
	cout << n2 << endl;

	//字符串倒序
	string str1, str2;
	str1 = "12345678";
	str2 = StrReverse(str1);
	cout << str2 << endl;

	//数字转换为字符串
	int n3;
	string str3;
	n3 = 12345678;
	str3 = Num2Str(n3);
	cout << str3 << endl;

	//字符串转换为数字
	string str4;
	int n4;
	str4 = "12345678";
	n4 = Str2Num(str4);
	cout << n4 << endl;

	system("pause");
	return 0;
}

//输出结果:
/*
87654321
87654321
12345678
12345678
请按任意键继续. . .
*/

你可能感兴趣的:(C/C++,数字倒序,字符串倒序,数字转换为字符串,字符串转换为数字)