2016-03-07 35 views
0

我試圖從數組中搜索一個來自服務器java的值。服務器在點擊一個按鈕後發送數據,並將該值接收到estratto這是一個char數組。 我需要找到estratto到字符串數組numeri或字符串變量number如何使用C++將值檢索到數組中?

我該怎麼做?

這裏是我的代碼: 「已找到」

char estratto[2048]; 
int pos=-1; 
char message[2048] = ""; 
//-- some code 

while(recv(sock, buff, sizeof(buff),0) > 0){ 
      strcat(message,buff); // received message form client 
     } 

//-- some code 

//-- divided message into a string array 
istringstream iss(message); 
    string token; 
    string numeri[15]; 
    int i=0,j=0,e=0; 

    while (std::getline(iss, token, ',')) 
    { 
     numeri[i]= token.c_str(); 
     i++; 
    } 



//-- the part that has problems 
    string number(message); 
    while(recv(sock, estratto, sizeof(estratto),0)>0){   
       for(i=0; i<15; i++){ 
        pos=number.find(estratto); 
        if(pos>0) 
         cout<<"TROVATO!"<<endl; 

        if(strcmp(numeri[i].c_str(),estratto)==0){ 
         trovati_cartella[i]=1; 
         cout<<"TROVATO!"<<endl;   
        } 
       } 
      } 

COUT < < endl; < < endl;如果我嘗試更改此代碼的某些部分,則不起作用。有人可以幫助我找到解決方案?

+0

你是什麼意思的「不工作」?你沒有得到任何輸出?錯誤的輸出?構建錯誤?請詳細說明並提供詳細信息。還包括所涉及的所有變量的類型,以及可能的初始化方式。 –

+0

哦,順便說一下,你知道C風格的字符串(我想你從服務器端收到的)應該由'\ 0'字符來終止嗎?您收到的數據是以這種方式終止的嗎? –

+0

@JoachimPileborg我看不到輸出'cout <<「Trovato!」 << endl;' –

回答

-1

我會修改這樣的代碼:

while(recv(sock, estratto, sizeof(estratto),0)>0){   
      for(i=0; i<15; i++){ 
       pos=number.find(estratto); 
       if(pos != std::string::npos) 
        cout<<"TROVATO!"<<endl; 

       if(strstr(numeri[i].c_str(),estratto) != NULL){ 
        trovati_cartella[i]=1; 
        cout<<"TROVATO!"<<endl;   
       } 
      } 
     } 

你的第一次檢查「POS> 0」是錯誤的,因爲如果estratto字符串包含到從指數0開始的串號,你的支票將無法找到它。 您的第二次檢查通過strcmp()函數來代替,只有當它與numeri [i]字符串完全匹配時,纔會捕獲estratto字符串,但如果它是子字符串,則不會。

+0

Downvote無法解決代碼的最大問題。 – SergeyA

+0

@SergeyA是什麼?爲什麼? –

+0

@SilviaB,因爲它已經告訴你nummeric次,當你打電話給你像你一樣閱讀時,你不知道'estratto'變量會是什麼。發送的字符串可能只有第一個字符,然後是垃圾。 – SergeyA

0

您是否遇到無符號vs有符號字符集問題。您可能需要使用64位編碼標準對字符串進行編碼和解碼。

相關問題