2016-03-07 71 views
-1

我需要搜索一個字符串到一個字符串數組。特別是,我有一個名稱的字符串變量,我需要將此名稱搜索到一個字符串數組,但我無法解決我的問題。如何使用C++將字符串搜索到字符串數組?

這裏是我的代碼:

connessionesocket(sock,server); 

    int result=0,f=0; 
    bool trovato=false; 
    do{ 

     if(result=(recv(sock, estratto, sizeof(estratto),0))>0) 
     { 
      string appo(estratto); 
      cout << "Appo: "<< appo<< endl; 
      if (std::find(std::begin(numeri), std::end(numeri), appo) != std::end(numeri)) 
      { 
        cout << "Correct" << endl; 
      } 
      f++;        
     }    

     if(result==0) 
     { 
      cout<< "Fine"; 
     } 
    } 
    while(result>0); 
    close(sock); 

是什麼問題?爲什麼我沒有看到cout << "Correct" <<endl;

這是我的結果:

I need, so the result is the same of the matrix to see the "Correct" message

+3

首先名[X]'和'appo'是'的std :: string's擺脫' strcmp'並使用'names [x] == appo' – NathanOliver

+1

回答,根據當前的上下文,很容易 - 'names'中的字符串都不匹配'appo'。 –

+0

@NathanOliver我試着做你告訴我的,但是,我的程序是一個客戶端/服務器,當我做'名稱[x] == appo'我的服務器停止工作.. –

回答

5

您可以使用標準算法std::find。例如

#include <algorithm> 

//... 

if (std::find(names, names + 15, appo) != names + 15) 
{ 
     cout << "Correct" << endl; 
} 

或者,如果如果`範圍對應於整個陣列然後

#include <algorithm> 
#include <iterator> 

//... 

if (std::find(std::begin(names), std::end(names), appo) != std::end(names)) 
{ 
     cout << "Correct" << endl; 
} 
+0

我有一個問題:當我啓動程序啓動錯誤,告訴我,開始和結束aren' st的成員..爲什麼? –

+0

@SilviaB您需要編譯至少啓用C++ 11才能使用它們。 – NathanOliver

+0

@NathanOliver感謝,但它不工作...我不知道爲什麼 –