为什么这个函数总是返回0?
我有一个总是返回0的函数。我相信的问题是数据是一个无符号的char,它不是库的一部分。它需要是无符号的字符。所以我该如何做这项工作,因为我没有。为什么这个函数总是返回0?
#include <string>
#include <iostream>
int Count(const std::string & str,
const std::string & obj) {
int a = 0;
int b = 0;
int c = 0;
int d = 0;
std::string ::size_type pos = 0;
while((pos = obj.find(str, pos))
!= std::string::npos) {
a++;
b++;
c++;
d++;
pos += str.size();
}
return a;
return b;
return c;
return d;
}
void printTcpContent(unsigned char *data,int)
{
std::string s = (const char*) data;
int a = Count("text/html", s);
int b = Count("text/plain", s);
int c = Count("image/jpg", s);
int d = Count("image/png", s);
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
std::cout << d << std::endl;
}
试试这个代码,而不是:
int Count(const std::string & strToFind,
const std::string & strToSearch) {
int n = 0;
std::string ::size_type pos = 0;
while((pos = strToSearch.find(strToFind, pos)) != std::string::npos) {
n++;
pos += strToSearch.size();
}
return n;
}
此外,您还可以通过使用更小的测试字符串调用它测试它的工作原理,如计数( “3”, “1234534”)
我试过了,它返回全零。我认为问题出在数据上。这是一个无符号的字符,Count不会重新调整它。所以在现实中它一无所获。 –
@ ME-dia:所以,事实上,你还没有把这个问题缩小到足以回答。请做一些调试。 –
@ ME-dia:您可以将诊断打印添加到计数以查看要处理的内容。 –
为什么你有四个变量做同样的事情?只有一个会得到回报。 – zellio
当您调用printTcpContent时,“data”的值是什么? –
数据返回此... ------------- IP数据开始------------- HTTP/1.1 200 OKP3P:policyref =“http:// g oogleads.g.doubleclick.net/pagead/gcn_p3p_.xml“ ,CP =”CURA ADMa DEVa TAOo PSAo PSDo OUR IND UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR“ Content-Type:text/HTML;字符集= UTF-8 X-的Content-Type-选项:nosniffContent- 编码:gipDate:星期一,8月29日201 1 21点19分36秒GMTServer:cafeCache - 控制:privateContent-长度:4863 X-XSS-保护:1; mode = block第二个响应。不正确我总是得到4回报。他们是正确的。 –