help with sscanf()!

Hi everybody,

i need help with this function, i'm programming in CGI with C and i can't make this work.

QUERY_STRING is something like: user=MYUSER&pass=MYPASS

So, what i want is to store the strings containing the username and the password into str1 and str2 respetively, here's the code:

#include <stdio.h>
#include <stdlib.h>
 
int main(void){
char *data, *str1, *str2;
 
/*... HTML stuff ...*/
 
data = getenv("QUERY_STRING");
 
if(data==NULL){
printf("<H1>Error passing data to CGI Script</H1>");
exit(1);
}
 
else
sscanf(data, "user=%s&pass=%s", &str1, &str2);
 
printf("Username: %s\n", str1);
printf("Password: %s\n", str2);
return(0);
}

But i'm getting an error... it works perfectly with numbers, but i need it to work like this, with strings.
Am i missing something? Please, help me!!!

firstly, you need to allocate space to str1 and str2.
secondly, are you sure that 'data' contains only 'user=foo&pass=bar'? Could there be something else?
Also you should check for the return status of the 'sscanf' to see what's up.

Thank you,

Yes, i'm totally sure that QUERY_STRING only contains that text, because it's generated by a form.

What do you mean with "allocate space to str1 and str2"?, sorry, but english isn't my mother language, so i'll appreciate if you could be more "graphical" please ;).

And, with the return... i've tried, but it doesn't tell me where the error is.

Please Help me!

int main(void){
char *data, str1[50], str2[50];
 
/*... HTML stuff ...*/
 
data = getenv("QUERY_STRING");
 
if(data==NULL){
printf("<H1>Error passing data to CGI Script</H1>");
exit(1);
}
 
else
sscanf(data, "user=%s&pass=%s", str1, str2);
 
printf("Username: %s\n", str1);
printf("Password: %s\n", str2);
return(0);
}

I did it,
I don't know why, but the string "user=%s&pass=%s" was creating a segmentation fault, what i did was specify which characters i wanted to seek, like this:

/* compile gcc file.c -o file.cgi
 * Get strings from html form
 */
 
#include <stdio.h>
#include <stdlib.h>
 
int main(void){
char *data, str1[12], str2[12];
printf("%s%c%c\n","Content-Type:text/html;charset=iso-8859-1",13,10);

data = getenv("QUERY_STRING");
if(data==NULL){
printf("<H1>Error passing data to CGI Script</H1>");
exit(1);
}
else
sscanf(data,"user=%[0-9a-zA-Z]&pass=%[0-9a-zA-Z]", &str1, &str2);
printf("Username: %s<BR>", str1);
printf("Password: %s<BR>", str2);
return(0);
}

This is it, Working, Thanks vgersh99 :wink: