Compare Version Numbers with StringStream

Compare Version Numbers with StringStream

The key here is using stringstream.

int compareVersion(string ver1, string ver2) {
    stringstream s1(ver1);
    stringstream s2(ver2);

    string v1, v2;
    while(!s1.eof() || !s2.eof()) {
        if (!s1.eof())
            getline(s1, v1, '.');
        else
            v1="0";
        if (!s2.eof())
            getline(s2, v2, '.');
        else
            v2="0";

        int n1=stoi(v1);
        int n2=stoi(v2);
        if (n1>n2) return 1;
        else if (n1<n2) return -1;
    }
    return 0;
}

This code compares version numbers by parsing each component between dots. When one version runs out of components, it treats missing parts as zero. This handles cases like comparing “1.0” with “1.0.0”.

#stl #string