ogs
ogs

Reputation: 1239

strcmp wrong usage?

I am using the following method in order to compare two versions of a same file.

fprintf(stdout, "ref_ptr %s\n", str);
fprintf(stdout, "cur_ptr %s\n", cur);

if (strcmp(cur, str) < 0) 
{
    fprintf(stderr,"Error: bad version!\n");
    return -1;
}

Output :

ref_ptr
01.100
01.020.21
cur_ptr 
01.100
01.000.46
Error: bad version!

In this specific case cur is not greater than str, why ?

It works fine when

ref_ptr
01.100
01.000.42

However, in the first case I would consider 46 > 21

Upvotes: 0

Views: 72

Answers (1)

Abstraction
Abstraction

Reputation: 511

strcmp finds the first mismatch between the strings (if it exists) and reports which string has greater value at the point of mismatch.

In your case the first mismatch is here

01.020.21 <- str
01.000.46 <- cur
    ^

Clearly 2>0 which means cur appears before str in the lexicographical order so the function call strcmp(cur, str) should return negative number.

int strcmp( const char *lhs, const char *rhs );

Return value

Negative value if lhs appears before rhs in lexicographical order. Zero if lhs and rhs compare equal. Positive value if lhs appears after rhs in lexicographical order.

Upvotes: 4

Related Questions