Why doesn't my code compare version numbers correctly?

It is supposed to return 1 if version 1 is greater than version 2, 0 if they are equal and -1 if version 1 is less than version 2. It does not work for all test cases however. What is missing and needs to be fixed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <string.h>
#include<iostream>
#include <vector>
#include <iterator>
#include <cctype>
#include <cstdlib>
#include<stdio.h>
#include<stdlib.h>

using namespace std;
/*
 * return 1 if v1 > v2
 * return 0 if v1 = v2
 * return -1 if v1 < v2
 */

int compareVersions(const char *v1, const char *v2)
{
    int i;
    int oct_v1[4], oct_v2[4];
    sscanf(v1, "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]);
    sscanf(v2, "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]);

    for (i = 0; i < 4; i++) {
        if (oct_v1[i] > oct_v2[i])
            return 1;
        else if (oct_v1[i] < oct_v2[i])
            return -1;
    }

    return 0;
}

int main()
{
   cout << compareVersions("1.0", "1.1") << endl;  // should return -1
   cout << compareVersions("2.0", "2.0.1") << endl; // should return -1
   cout << compareVersions("2.0", "2.0") << endl; // should return 0
   cout << compareVersions(".0.2", ".0.1") << endl; // should return 1
}
Your compareVersions function always extracts and compares 4 values. None of your test cases have 4 values to extract. (sscanf doesn't do what you want for that last test case.)

Helpful hint: sscanf returns a value.



Last edited on
I suppose that the numbers that sscanf() failed to read would remain unchanged.
Check the return value of sscanf() and loop on that.
Topic archived. No new replies allowed.