该函数浏览添加到缓冲区中的字符串并搜索指定的字段。如果在缓冲区中找到该字段,则返回指向所分配内容的指针。如果在缓冲区内找不到指定的字段,则指向“?”的指针字符串被传送。在缓冲区中查找字符串
#include <stdio.h>
#include <string.h>
char buf[256] = "ID=1234 Name=Manavendra Nath Manav Age=30";
const char * get_info (const char *name)
{
unsigned nl;
const char *p, *e;
if(name!=NULL)
{
nl = strlen(name);
for (p = buf, e = p + strlen(buf) ; p < e && p[0] ; p += strlen(p) + 1) {
printf("p = %s\tname = %s\te = %s\n", p, name, e);
if (strncmp (p, name, nl) == 0 && p[nl] == '=')
return (p + nl + 1);
}
}
return "?";
}
int main()
{
printf("strlen(buf) = %d\n", strlen(buf));
printf("%s\n", get_info("Nath"));
return 0;
}
执行后,我总是得到?
作为输出,代码有什么问题?另外请注意,在上面的代码中用sizeof
代替strlen
是否可取? sizeof(buf)
返回256
。
[email protected]:~/programs/test$ ./a.out
strlen(buf) = 21
p = Manavendra Nath Manav name = Nath e =
?
编辑:对不起,我没有更新大约p[nl] == '='
之前。如果缓冲区类似于 char buf[256] = "ID=1234 Name=Manavendra Nath Manav Age=30";
则 get_info("Name")
应返回Manavendra Nath Manav
。
从你的描述,这听起来像你只是想编写[的strstr(HTTP:// en.cppreference.com/w/c/string/byte/strstr),但这不是你的代码所做的。你能证明你的结果是什么吗? – Useless
是否允许使用C++? – TemplateRex