C++ 软件版本号对比

原文链接: https://blog.csdn.net/hellokandy/article/details/78017827

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/hellokandy/article/details/78017827

在软件更新时,需要根据版本号来决定是否需要自动更新,所以就涉及到版本号的对比了。

下面给出的是使用string的compare函数进行版本号判断的代码:
 

#include "stdafx.h"
#include 
#include 
using namespace std;
 
 
vector split_wstring(wstring &szInput, wstring &szToken)
{
	vector result;
	int pos = 0;
	int begin = 0;
	const int size = szToken.size();
	while (true)
	{
		pos = szInput.find(szToken, begin);
		if (pos == wstring::npos)
		{
			result.push_back(szInput.substr(begin));
			break;
		}
		result.push_back(szInput.substr(begin, pos - begin));
		begin = pos + size;
	}
	return result;
}
 
//retval: 0:相等;1:大于服务器版本,-1:小于服务器版本,2:版本字段数不一致
int CompareVersion(std::wstring wszLoc, std::wstring wszSvr)
{
	//
	std::vector locVerFields = split_wstring(wszLoc, std::wstring(L"."));
	std::vector srvVerFields = split_wstring(wszSvr, std::wstring(L"."));
 
	int loc_size = locVerFields.size();
	int srv_size = srvVerFields.size();
	if (loc_size != srv_size)
	{
		return 2;
	}
 
	int retval = 0;
	for(int i=0; i < locVerFields.size(); i++)
	{
		int istrcmp = 0;
		istrcmp = locVerFields[i].compare(srvVerFields[i]);
		if ( istrcmp == 0 )
		{
			if (i == locVerFields.size()-1)//最后一个
			{
				retval = 0;
				break;
				//return 0;
			}
		}
		else if( istrcmp == 1)
		{
			retval = 1;
			break;
			//return 1;
		}
		else if (istrcmp < 0)
		{
			retval = -1;
			break;
			//return -1;
		}
	}
	return retval;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
	std::wstring wszLocal = L"1.2.3.14";
	std::wstring wszServer = L"1.2.3.15";
	int res = CompareVersion(wszLocal, wszServer);
 
	printf("%d\r\n", res);
	system("pause");
 
	return 0;
}

 

你可能感兴趣的:(c++笔记)