我的 sscanf 格式有什么问题

What is wrong with my sscanf format

我在这里尝试用 c 处理表单数据。

fgets(somedata, bufferone, stdin);  

如果我 printf 'somedata',我得到:

username=John&password=hispass123

现在,当我尝试使用

进行 sscanf 时
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);

比我得到的

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

我怀疑,第一个调用读取到空终止符,然后第二个调用溢出或什么的。

所以我需要格式方面的帮助。另外,sscanf 函数是这种情况下的最佳选择吗?我正在尝试从消息正文中获取 2 个字符串(以 html 形式通过标准输入发送)。

"%s" 是贪婪的。它会拾取其路径中不是空白字符的所有内容。将其更改为使用 "%[^&]".

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

格式说明符的 %[^&] 部分将提取 而非 字符 & 的任何字符。遇到&.

就会停止提取

为了使您的代码更加健壮,请始终检查 sscanf/fscanf 的 return 值。

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