我的sscanf格式有什么问题 [英] What is wrong with my sscanf format
问题描述
我正在这里处理c中的表单数据。
I'm trying to deal with form data in c here.
fgets(somedata, bufferone, stdin);
如果我printf'somedata',我得到:
if I printf 'somedata', I get:
username=John&password=hispass123
现在当我尝试使用
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
我怀疑,第一个调用读取的是空终止符,然后第二个调用溢出之类的。
I suspect, the first call reads up to the null-terminator, and then second call overflows or something.
所以我需要有关格式的帮助。另外,在这种情况下sscanf函数是最佳选择吗?我正在尝试从邮件正文中获取2个字符串(由html表单通过stdin发送)。
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).
推荐答案
%s
是贪婪的。它拾取路径中不是空格字符的所有内容。将其更改为使用%[^&]
。
"%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 &
.
为使代码更健壮,请始终检查返回值 sscanf / fscanf
。
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);
}
这篇关于我的sscanf格式有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!