3

I want to compare my string to a giving format.

the format that I want to use in the check is :

"xxx://xxx:xxx@xxxxxx" // all the xxx are with variable length

so I used the sscanf() as follow :

if (sscanf(stin,"%*[^:]://%*[^:]:%*[^@]@") == 0) { ... }

is it correct to compare the return of scanf to 0 in this case?

Anis_Stack
  • 3,306
  • 4
  • 30
  • 53
  • 2
    i think it would be more robust to use `strtok` instead, that way you could say what is wrong with the string e.g. domain name missing – AndersK Nov 26 '13 at 11:20
  • See this question: http://stackoverflow.com/q/726122/694576 and its answers for alternative approaches to pars/check a URL/URI. – alk Nov 26 '13 at 11:35

2 Answers2

1

You will only get zero back if all the fields match; but that won't tell you diddly-squat in practice. It might have failed with a colon in the first character and it would still return 0.

You need at least one conversion in there that is counted (%n is not counted), and that occurs at the end so you know that what went before also matched. You can never tell if trailing context (data after the last conversion specification) matched, and sscanf() won't backup if it has converted data, even if backing up would allow the trailing context to match.

For your scenario, that might be:

char c;
int  n;

if (sscanf(stin, "%*[^:]://%*[^:]:%*[^@]@%n%c", &n, &c) == 1)

This requires at least one character after the @. It also tells you how many characters there were up to and including the @.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

OP's suggestion is close.

@Jonathan Leffler is correct in that comparing the result of a specifier-less sscanf() against 0 does not distinguish between a match and no-match.

To test against "xxx://xxx:xxx@xxxxxx", (and assuming any part with "x" needs at least 1 matching), use

int n = 0;
sscanf(stin, "%*[^:]://%*[^:]:%*[^@]@%*c%n", &n);
if (n > 0) {
  match();
}

There is a obscure hole using this method with fscanf(). A stream of data with a \0 is a problem.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256