Search code examples
c++parsingversion-numbering

How to parse version number to compare it?


SCENARIO: I have a simple application that checks its RSS feed and looks if there's a newer version available. Thus, I want to check if the current version is less than the one present on the RSS feed. Ideally as simple as:

CURRENTVERSION < updateVersion

PROBLEM: The versioning consists of major.minor.revision.build and I don't know how to parse this into a number to perform the version check.

These are the parameters to compare:

#define CURRENTVERSION = 0,2,5,1

The version downloaded from the web is "0.2.6.1" ( as a string).

What would be the best way to check if one is less than the other?

I've tried converting it to a double, but the value becomes 0.2 (only the first . is being parsed, rest is ignored).

CONSTRAINT: It must not be a solution using .NET libraries as the application must work when no .NET framework is present.

(EDIT) I settled for the following solution, thanks to Karthik T's answer.

struct Version
{
    Version(string versionStr)
    {
        sscanf(versionStr.c_str(), "%d.%d.%d.%d", &major, &minor, &revision, &build);
    }

    bool operator<(const Version &otherVersion)
    {
        if(major < otherVersion.major)
            return true;
        if(minor < otherVersion.minor)
            return true;
        if(revision < otherVersion.revision)
            return true;
        if(build < otherVersion.build)
            return true;
        return false;
    }

    int major, minor, revision, build;
};

Solution

  • struct Version{
        Version(std::string versionStr);     //remember to use  versionStr.c_str() if using C functions like sscanf or strtok
        bool operator<(const Version &other); // could and perhaps should be a free function
    
        int major,minor,revision,build;
    };
    
    
    bool needtoUpdate = Version(CURRENTVERSION)<Version(latestVersion);
    

    Please fill in the definitions.

    Also, your #define is a mistake. You want it like below. Or use a const char * if you can.

    #define CURRENTVERSION "0.2.5.1"
    

    You can use sscanf or something like strtok to parse in the constructor.