1. 程式人生 > >C++常用程式碼(一),int,string等常見型別轉換

C++常用程式碼(一),int,string等常見型別轉換

#ifndef GBK_H_
#define GBK_H_

#include <QString>
#include <QTextCodec>
#include <string>
#include <iostream>
#include <sstream>

using std::string;

class GBK
{
public:
	// QString(Unicode) -> std::string (GBK)
	static string FromUnicode(const QString& qstr)
	{
		QTextCodec* pCodec = QTextCodec::codecForName("gb2312");
		if(!pCodec) return "";	

		QByteArray arr = pCodec->fromUnicode(qstr);
		string cstr = arr.data();
		return cstr;
	}

	// std::string (GBK) -> QString(Unicode)
	static QString ToUnicode(const string& cstr)
	{
		QTextCodec* pCodec = QTextCodec::codecForName("gb2312");
		if(!pCodec) return "";

		QString qstr = pCodec->toUnicode(cstr.c_str(), cstr.length());
		return qstr;
	}

	// int -> string(Unicode)
	static string IntToString(const int &nParam)  
	{  
		std::stringstream sstream;  
		sstream<<nParam;  
		return sstream.str();
	}  

	// string(Unicode) -> int
	static int StringToInt(const string &strs)  
	{  
		int int_temp = 0;
		std::stringstream stream(strs);  
		stream>>int_temp;
		return int_temp;
	}  
};

#endif // GBK_H_