What is wrong with my sscanf format

六眼飞鱼酱① 提交于 2019-12-31 05:07:11

问题


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).


回答1:


"%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);
}


来源:https://stackoverflow.com/questions/51542403/what-is-wrong-with-my-sscanf-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!