2011-09-08 139 views
-6

我有一個總是返回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; 
} 
+3

爲什麼你有四個變量做同樣的事情?只有一個會得到回報。 – zellio

+0

當您調用printTcpContent時,「data」的值是什麼? –

+0

數據返回此... ------------- 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回報。他們是正確的。 –

回答

0

試試這個代碼,而不是:

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」)

+0

我試過了,它返回全零。我認爲問題出在數據上。這是一個無符號的字符,Count不會重新調整它。所以在現實中它一無所獲。 –

+1

@ ME-dia:所以,事實上,你還沒有把這個問題縮小到足以回答。請做一些調試。 –

+0

@ ME-dia:您可以將診斷打印添加到計數以查看要處理的內容。 –