1. 程式人生 > >數字與字串:倒序和相互轉換

數字與字串:倒序和相互轉換

//原始碼已在VS2010編譯通過
#include <iostream>
#include <sstream>
#include <string>
#include <windows.h>
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
請按任意鍵繼續. . .
*/