【发布时间】:2013-01-24 10:31:07
【问题描述】:
此函数浏览添加到缓冲区中的字符串并搜索指定字段。如果在缓冲区中找到该字段,则返回指向分配内容的指针。如果在缓冲区内未找到指定字段,则指向“?”的指针字符串已交付。
#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;
}
执行后,我总是得到? 作为输出,代码有什么问题?第二点,在上面的代码中将strlen 替换为sizeof 是否可取? sizeof(buf) 返回256。
manav@os-team:~/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,但这不是您的代码所做的。你能展示你想要的结果吗?
-
你可以使用C++吗?