【问题标题】:How to search a string into a string array using c++?如何使用 C++ 将字符串搜索到字符串数组中?
【发布时间】:2016-03-07 14:20:55
【问题描述】:

我需要将一个字符串搜索到一个字符串数组中。特别是,我有一个带有名称的字符串变量,我需要将此名称搜索到一个字符串数组中,但我无法解决我的问题。

这是我的代码:

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 &lt;&lt; "Correct" &lt;&lt;endl;

这是我的结果:

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

【问题讨论】:

  • 首先如果names[x]appostd::strings 摆脱strcmp 并使用names[x] == appo
  • 在给出当前上下文的情况下很容易回答 - names 中的字符串都不匹配 appo
  • @NathanOliver 我试着照你说的做,但是,我的程序是一个客户端/服务器,当我做 names[x]==appo 我的服务器停止工作..
  • @SilviaB 那么您的代码中还有一些其他问题,例如您的 15 的任意限制不正确
  • 那我觉得你有更大的问题。将您的代码更改为 names[x]==appo 应该不会对代码的工作方式产生明显的影响,希望它可以清楚地说明您在源代码中所做的事情。

标签: c++ arrays string algorithm


【解决方案1】:

您可以使用标准算法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;  
}   

【讨论】:

  • 我有一个问题:当我启动程序时,错误告诉我 begin 和 end 不是 std 的成员。为什么?
  • @SilviaB 您需要至少启用 c++11 进行编译才能使用它们。
  • @NathanOliver 谢谢,但它不起作用......我不知道为什么
  • @SilviaB 还要检查你是否包含了标题
  • 我添加了所有库@VladfromMoscow
猜你喜欢
  • 2022-01-23
  • 2011-07-22
  • 2021-09-15
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多