1. 程式人生 > >一個簡單的命令列解析類

一個簡單的命令列解析類

struct USER_COMMAND
{
public:
	USER_COMMAND(CString m_strCmd)
	{
		int iIndex1 = 0, iIndex2 = 0;
		while(1)
		{
			iIndex2 = m_strCmd.Find(_T(' '), iIndex1);
			if(iIndex2 == -1)
			{
				AddCmd(m_strCmd.Mid(iIndex1));
				break;
			}
			else
			{
				AddCmd(m_strCmd.Mid(iIndex1, iIndex2-iIndex1));
				iIndex1 = iIndex2 + 1;
			}
		}
	}

	~USER_COMMAND()
	{
		Reset();
	}

	CString GetParam(int index)
	{
		if(index >= GetSize())
		{
			return _T("");
		}
		else
		{
			return m_vectorCmd[index];
		}
	}

private:
	inline void Reset()
	{
		m_vectorCmd.clear();
		m_iCmdCount = 0;
	}

	inline void AddCmd(CString& m_strCmd)
	{
		m_vectorCmd.push_back(m_strCmd);
		m_iCmdCount++;
	}

	inline int GetSize() const
	{
		return m_vectorCmd.size();
	}

public:
	std::vector<CString>		m_vectorCmd;
	int							m_iCmdCount;
};

傳進命令列字串(空格分割),之後GetParam()就可以了。