Ahmad Bilal
Ahmad Bilal

Reputation: 382

What is wrong with my sscanf format

I'm trying to deal with form data in c here.

fgets(somedata, bufferone, stdin);  

if I printf 'somedata', I get:

username=John&password=hispass123

now when I try to sscanf using

char usr[100], pass[100];
sscanf(somedata, "username=%s&password=%s", usr, pass);
printf("Content-type: text/html\n\n");
printf("%s is value 1\n", usr);
printf("%s is value 2\n", pass);

than I get

John&password=hispass123 is value 1
?? is value 2

I suspect, the first call reads up to the null-terminator, and then second call overflows or something.

So I need help with the format. Also, is sscanf function the best choice in this scenario? I'm trying to obtain 2 strings from the message body (sent via stdin by the html form).

Upvotes: 0

Views: 740

Answers (1)

R Sahu
R Sahu

Reputation: 206667

"%s" is greedy. It picks up everything in its path that is not a whitespace character. Change it to use "%[^&]".

sscanf(somedata, "username=%[^&]&password=%s", usr, pass);

The %[^&] part of the format specifier will extract any character that is not the character &. It will stop extracting when it encounters a &.

To make your code a bit more robust, always check the return value of sscanf/fscanf.

int n = sscanf(somedata, "username=%[^&]&password=%s", usr, pass);
if ( n != 2 )
{
   // There was a problem reading the data.
}
else
{
   // Reading was successful. Use the data.
   printf("Content-type: text/html\n\n");
   printf("%s is value 1\n", usr);
   printf("%s is value 2\n", pass);
}

Upvotes: 4

Related Questions